[Leetcode] Maximum Gap

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.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

桶排序,由于num中的数字肯定在[min,max]区间内,所以根据抽屉原理,假设num中有n个数字,则最大的gap必然要大于dis=(max-min)/(n-1),所以我们可以把num所在的范围分成等间隔的区间,相邻区间内的元素之间的最大差值,即为要寻找的gap。

 1 class Solution {
 2 public:
 3     int maximumGap(vector<int> &num) {
 4         int n = num.size();
 5         if (n < 2) return 0;
 6         if (n == 2) return abs(num[0] - num[1]);
 7         int imin = num[0], imax = num[0];
 8         for (int i = 0; i < n; ++i) {
 9             imin = min(imin, num[i]);
10             imax = max(imax, num[i]);
11         }
12         int dist = (imax-imin) / n + 1;
13         vector<vector<int> > bucket((imax-imin)/dist + 1);
14         int idx;
15         for (int i = 0; i < n; ++i) {
16             idx = (num[i] - imin) / dist;
17             if (bucket[idx].empty()) {
18                 bucket[idx].push_back(num[i]);
19                 bucket[idx].push_back(num[i]);
20             } else {
21                 bucket[idx][0] = min(bucket[idx][0], num[i]);
22                 bucket[idx][1] = max(bucket[idx][1], num[i]);
23             }
24         }
25         int gap = 0, pre = 0, tmp;
26         for (int i = 1; i < bucket.size(); ++i) {
27             if (bucket[i].empty()) continue;
28             tmp = bucket[i][0] - bucket[pre][1];
29             gap = max(gap, tmp);
30             pre = i;
31         }
32         return gap;
33     }
34 };

 

posted @ 2015-03-21 16:15  Eason Liu  阅读(1031)  评论(0编辑  收藏  举报