LeetCode [Sort]: 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.
From Discuss, the algorithm of Bucket sort: https://oj.leetcode.com/discuss/18499/bucket-sort-java-solution-with-explanation-o-time-and-space
The idea is as follows: the array contains N elements, the minimum element is min, and the maximum element is max. The maximum spacing is not less than ceil (max-min) /(N-1 )). (Ceil (x) refers to the smallest integer not less than x ). Assuming the average spacing is gap = ceil (max-min)/(N-1), put all the elements into the N-1 bucket, k (0 <= k <= N-2) put all elements in the bins in the interval [min + k * gap, min + (k + 1) * gap. So except for the maximum element max and the smallest element min, the remaining N-2 elements are put into this N-1 bucket, so at least one bucket is empty, we only need to store the largest and smallest elements in each bucket to calculate the maximum spacing.
The C ++ code is implemented as follows:
int maximumGap(vector
&num) { if (num.empty() || num.size() == 1) return 0; int min = num[0], max = num[0]; for (auto n : num) { if (n < min) min = n; if (n > max) max = n; } int gap = (max - min - 1) / (num.size() - 1) + 1; vector
bucketMins(num.size() - 1, INT_MAX); vector
bucketMaxs(num.size() - 1, INT_MIN); for (auto n : num) { if (n != min && n != max) { int bucketIdx = (n - min) / gap; if (n < bucketMins[bucketIdx]) bucketMins[bucketIdx] = n; if (n > bucketMaxs[bucketIdx]) bucketMaxs[bucketIdx] = n; } } int maxGap = INT_MIN, prev = min; for (int i = 0; i < num.size() - 1; ++i) { if (bucketMins[i] == INT_MAX && bucketMaxs[i] == INT_MIN) continue; if (bucketMins[i] - prev > maxGap) maxGap = bucketMins[i] - prev; prev = bucketMaxs[i]; } return std::max(max - prev, maxGap); }
The time performance is as follows: