164. Maximum Gap
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.
* You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
* Try to solve it in linear time/space.
class Solution {
public:
struct Bucket
{
bool used;
int minv;
int maxv;
Bucket():used(false), minv(INT_MAX), maxv(INT_MIN)
{}
};
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2)
return 0;
//桶中數據記錄映射到該桶的最大值和最小值
int minv = *min_element(nums.begin(), nums.end());
int maxv = *max_element(nums.begin(), nums.end());
int bucketSize = max(1, (maxv - minv) / (n-1));//桶大小(容量)
int bucketNum = (maxv-minv) / bucketSize + 1;//桶數量
vector<Bucket> buckets(bucketNum);
for (auto num : nums)
{
int index = (num - minv) / bucketSize; //映射到同1個桶中的數
buckets[index].used = true;
buckets[index].minv = min(num, buckets[index].minv);
buckets[index].maxv = max(num, buckets[index].maxv);
}
int prev = minv, maxgap = 0;
for (auto bucket : buckets)
{
if (!bucket.used)
continue;
maxgap = max(maxgap, bucket.minv - prev);
prev = bucket.maxv;
}
return maxgap;
//基數排序
#if 0
int maxv = *max_element(nums.begin(), nums.end());
int exp = 1;
int radix = 10;
vector<int> tmp(n);
int count[10];
while (maxv / exp) //從個位開始依次到最高位排序
{
memset(count, 0, sizeof(count));
for (int i = 0; i < n; i++)
count[nums[i] / exp % 10]++;
for (int i = 1; i < 10; i++)
count[i] += count[i-1]; //更大的數排位更高
for (int i = n-1; i >= 0; i—)//從後更新,保證排序的穩定性(相同大小的數位置不變)
tmp[--count[nums[i] / exp % 10]] = nums[i];
for (int i = 0; i < n; i++)
nums[i] = tmp[i];
exp *= 10;
}
int res = INT_MIN;
for (int i = 1; i < n; i++)
res = max(res, nums[i]-nums[i-1]);
return res;
#endif
}
};