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.
基本思路:
先求出无序数组中的最大值和最小值。
当每个数,都等距离分布时,此时将取得max gap的下限值。
span = ceiling[(B - A) / (N - 1)]
其中,B为最小值,A为最大值,N为元素个数
如果以此span作为一个桶的取值范围。 并将数分配进这些桶内。
那么在同一个桶内的数,之间的有序gap,将不会超过span。则桶内的数的,彼此之间就不用再求gap。
只需要计算桶与桶之间的gap,并保留最大值。
而桶与桶之间的gap,则是后一桶的最小值,与 前一桶的最大值之间的差值。
故在分配时,只需要记住该桶内的最小值,和最大值。
class Solution {
public:
int maximumGap(vector<int>& nums) {
if (nums.size() < 2)
return 0;
int minV = nums[0];
int maxV = nums[0];
for (auto i: nums) {
if (i < minV)
minV = i;
else if (i > maxV)
maxV = i;
}
if (maxV == minV)
return 0;
int span = (maxV-minV) / (nums.size()-1);
span = max(1, span);
int buckets_count = (maxV-minV)/span;
++buckets_count;
vector<int> buckets_min(buckets_count, INT_MAX);
vector<int> buckets_max(buckets_count, INT_MIN);
for (auto i: nums) {
int slot = (i-minV) / span;
buckets_min[slot] = min(buckets_min[slot], i);
buckets_max[slot] = max(buckets_max[slot], i);
}
int gap = 0;
int last_max = buckets_max[0];
for (int i=1; i<buckets_count; i++) {
if (buckets_max[i] != INT_MIN) {
gap = max(gap, buckets_min[i]-last_max);
last_max = buckets_max[i];
}
}
return gap;
}
};
原文地址:http://blog.csdn.net/elton_xiao/article/details/46581363