Maximum Gap (ARRAY - SORT)
QUESTION
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.
1ST TRY
桶排序
class Solution { public: int maximumGap(vector<int> &num) { if(num.empty() || num.size() < 2) return 0; int maxNum = *max_element(num.begin(), num.end()); int minNum = *min_element(num.begin(), num.end()); //bucket gap: 假设每个数一个桶,两个桶之间的平均差值 int gap = ceil((double)(maxNum - minNum)/(num.size()-1)); //number of buckets int bucketNum = (maxNum-minNum)/gap+1; //declare buckets vector<int> bucketsMin(bucketNum, INT_MAX); vector<int> bucketsMax(bucketNum, INT_MIN); //put into buckets for(int i = 0; i < num.size(); i ++) { int buckInd = (num[i]-minNum)/gap; //匹配到bucket bucketsMin[buckInd] = min(bucketsMin[buckInd], num[i]); bucketsMax[buckInd] = max(bucketsMax[buckInd], num[i]); } //i_th gap is minvalue in i+1_th bucket minus maxvalue in i_th bucket int maxGap = INT_MIN; int previous = minNum; for(int i = 0; i < bucketNum; i ++) { if(bucketsMin[i] == INT_MAX && bucketsMax[i] == INT_MIN) continue; //empty maxGap = max(maxGap, bucketsMin[i]-previous); previous = bucketsMax[i]; } return maxGap; } };
Result: Accepted