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.

利用桶排序来缩减分隔距离,减少内存消耗

  1. int maximumGap(vector<int> &num) {
  2. unsigned int nSize = num.size();
  3. if(nSize < 2) return 0;
  4. int maxNum = *max_element(num.begin(),num.end());
  5. int minNum = *min_element(num.begin(),num.end());
  6. int gap = (int)ceil((double)(maxNum - minNum)/(nSize-1));
  7. int bucketNum = (int)ceil((double)(maxNum-minNum)/gap);
  8. vector<int> minBucket(bucketNum,INT_MAX);
  9. vector<int> maxBucket(bucketNum,INT_MIN);
  10. for(int i=0;i<nSize;i++) {
  11. if(num[i] == maxNum || num[i] == minNum) {
  12. continue;
  13. }
  14. int bucketId = (num[i]-minNum)/gap;
  15. minBucket[bucketId] = min(minBucket[bucketId],num[i]);
  16. maxBucket[bucketId] = max(maxBucket[bucketId],num[i]);
  17. }
  18. int maxGap = INT_MIN;
  19. int previous = minNum;
  20. for(int i=0;i<bucketNum;i++) {
  21. if(minBucket[i] == INT_MAX && maxBucket[i] == INT_MIN) {
  22. continue;
  23. }
  24. maxGap = max(maxGap,minBucket[i]-previous);
  25. previous = maxBucket[i];
  26. }
  27. maxGap = max(maxGap,maxNum-previous);
  28. return maxGap;
  29. }
posted @ 2014-12-16 14:59  purejade  阅读(83)  评论(0)    收藏  举报