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.
利用桶排序来缩减分隔距离,减少内存消耗
- int maximumGap(vector<int> &num) {
- unsigned int nSize = num.size();
- if(nSize < 2) return 0;
- int maxNum = *max_element(num.begin(),num.end());
- int minNum = *min_element(num.begin(),num.end());
- int gap = (int)ceil((double)(maxNum - minNum)/(nSize-1));
- int bucketNum = (int)ceil((double)(maxNum-minNum)/gap);
- vector<int> minBucket(bucketNum,INT_MAX);
- vector<int> maxBucket(bucketNum,INT_MIN);
- for(int i=0;i<nSize;i++) {
- if(num[i] == maxNum || num[i] == minNum) {
- continue;
- }
- int bucketId = (num[i]-minNum)/gap;
- minBucket[bucketId] = min(minBucket[bucketId],num[i]);
- maxBucket[bucketId] = max(maxBucket[bucketId],num[i]);
- }
- int maxGap = INT_MIN;
- int previous = minNum;
- for(int i=0;i<bucketNum;i++) {
- if(minBucket[i] == INT_MAX && maxBucket[i] == INT_MIN) {
- continue;
- }
- maxGap = max(maxGap,minBucket[i]-previous);
- previous = maxBucket[i];
- }
- maxGap = max(maxGap,maxNum-previous);
- return maxGap;
- }

浙公网安备 33010602011771号