Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Notice
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Given [1, 9, 2, 5]
, the sorted form of it is [1, 2, 5, 9]
, the maximum gap is between 5
and 9
= 4
.
分析:http://bookshadow.com/weblog/2014/12/14/leetcode-maximum-gap/
假设有N个元素,最小是A, 最大是B。那么最大差值一定大于interval = (1.0 * max - min) / num.length。
我们需要num.length + 1个桶 (0 to num.length),令每个bucket(桶)的大小为interval,对于数组中的任意整数K,很容易通过算式loc = (K - A) / interval 找出其桶的位置,然后维护每一个桶的最大值和最小值.
1 class Solution { 2 /** 3 * @param nums: 4 * an array of integers 5 * @return: the maximum difference 6 */ 7 public int maximumGap(int[] num) { 8 if (num == null || num.length < 2) return 0; 9 10 int max = num[0], min = num[0]; 11 for (int i = 1; i < num.length; i++) { 12 max = Math.max(max, num[i]); 13 min = Math.min(min, num[i]); 14 } 15 16 if (max - min <= 1) return max - min; 17 18 // the max gap is absolutely greater than (1.0 * max - min) / num.length 19 // so the interval below can guarantee the maximu gap values in two different buckets. 20 double interval = (1.0 * max - min) / num.length; 21 22 Bucket[] buckets = new Bucket[num.length + 1]; // project to (0 - n) 23 for (int i = 0; i < buckets.length; i++) { 24 buckets[i] = new Bucket(); 25 } 26 27 // distribute every number to a bucket array 28 for (int i = 0; i < num.length; i++) { 29 int index = (int)((num[i] - min) / interval); 30 31 if (buckets[index].low == -1) { 32 buckets[index].low = num[i]; 33 buckets[index].high = num[i]; 34 } else { 35 buckets[index].low = Math.min(buckets[index].low, num[i]); 36 buckets[index].high = Math.max(buckets[index].high, num[i]); 37 } 38 } 39 40 // scan buckets to find maximum gap 41 int result = 0; 42 int prev = buckets[0].high; 43 for (int i = 1; i < buckets.length; i++) { 44 if (buckets[i].low != -1) { 45 result = Math.max(result, buckets[i].low - prev); 46 prev = buckets[i].high; 47 } 48 49 } 50 51 return result; 52 } 53 } 54 55 class Bucket { 56 int low; 57 int high; 58 59 public Bucket() { 60 low = -1; 61 high = -1; 62 } 63 }