您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Maximum Gap

2015-06-26 23:37 701 查看

Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

https://leetcode.com/problems/maximum-gap/

这道题正确的姿势是先随便写一把快排交过了,然后去看Solution。 233

原版Solution解释得很清楚了,抽屉原理+箱排序。

Suppose there are N elements and they range from A to B.

Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

Analysis written by @porker2008.

/**
* @param {number[]} nums
* @return {number}
*/
var maximumGap = function(nums) {
if(nums.length < 2){
return 0;
}
var boxMap = {};
var max = Math.max.apply(null, nums);
var min = Math.min.apply(null, nums);
var vol = parseInt((max - min) / (nums.length - 1));
if(vol === 0){
vol = 1;
}

var i = 0, box = null, curr = null;
for(i = 0; i < nums.length; i++){
curr = nums[i];
box = parseInt((curr - min) / vol);
if(!boxMap[box]){
boxMap[box] = {max : curr, min : curr};
}else{
if(curr > boxMap[box].max){
boxMap[box].max = curr;
}else if(curr < boxMap[box].min){
boxMap[box].min = curr;
}
}
}

var maxGap = -Infinity;
var previousMax = null;
for(i in boxMap){
if(previousMax && (boxMap[i].max - previousMax)> maxGap){
maxGap = boxMap[i].min - previousMax;
}
previousMax = boxMap[i].max;
}
return maxGap;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: