您的位置:首页 > 其它

LeetCode – Refresh – Maximum Gap

2015-03-21 05:47 295 查看
Sorting solution O(nlogn):

class Solution {
public:
int maximumGap(vector<int> &num) {
int len = num.size(), result = 0;
if (len < 2) return 0;
sort(num.begin(), num.end());
for (int i = 0; i < len-1; i++){
result = max(result, num[i+1] - num[i]);
}
return result;
}
};


O(n), bucket sort. The hint gets from leetcode:

Suppose there are N elements and they range from A to B.

Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

Analysis written by @porker2008.

class Solution {
public:
int maximumGap(vector<int> &num) {
int len = num.size(), result = 0, gMax = INT_MIN, gMin = INT_MAX, blen = 0, index = 0;
if (len < 2) return 0;
for (int i : num) {
gMin = min(gMin, i);
gMax = max(gMax, i);
}
blen = (gMax - gMin)/len + 1;
vector<vector<int> > buckets((gMax - gMin)/blen + 1);
for (int i : num) {
int range = (i - gMin)/blen;
if (buckets[range].empty()) {
buckets[range].reserve(2);
buckets[range].push_back(i);
buckets[range].push_back(i);
} else {
if (i < buckets[range][0]) buckets[range][0] = i;
if (i > buckets[range][1]) buckets[range][1] = i;
}
}
for (int i = 1; i < buckets.size(); i++) {
if (buckets[i].empty()) continue;
result = max(buckets[i][0] - buckets[index][1], result);
index = i;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: