[LeetCode][JavaScript]Maximum Gap
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.
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var maximumGap = function(nums) { 6 if(nums.length < 2){ 7 return 0; 8 } 9 var boxMap = {}; 10 var max = Math.max.apply(null, nums); 11 var min = Math.min.apply(null, nums); 12 var vol = parseInt((max - min) / (nums.length - 1)); 13 if(vol === 0){ 14 vol = 1; 15 } 16 17 var i = 0, box = null, curr = null; 18 for(i = 0; i < nums.length; i++){ 19 curr = nums[i]; 20 box = parseInt((curr - min) / vol); 21 if(!boxMap[box]){ 22 boxMap[box] = {max : curr, min : curr}; 23 }else{ 24 if(curr > boxMap[box].max){ 25 boxMap[box].max = curr; 26 }else if(curr < boxMap[box].min){ 27 boxMap[box].min = curr; 28 } 29 } 30 } 31 32 var maxGap = -Infinity; 33 var previousMax = null; 34 for(i in boxMap){ 35 if(previousMax && (boxMap[i].max - previousMax)> maxGap){ 36 maxGap = boxMap[i].min - previousMax; 37 } 38 previousMax = boxMap[i].max; 39 } 40 return maxGap; 41 };