您的位置:首页 > 其它

leetcode[164] Maximum Gap

2014-12-21 01:03 302 查看
梅西刚梅开二度,我也记一题。

在一个没排序的数组里,找出排序后的相邻数字的最大差值。

要求用线性时间和空间。

如果用nlgn的话,直接排序然后判断就可以了。so easy

class Solution {
public:
int maximumGap(vector<int> &num) {
if (num.size() < 2) return 0;
int Max = num[0], Min = Max, ans = 0;
for (int i = 1; i < num.size(); i++)
{
if (num[i] < Min)
Min = num[i];
if (num[i] > Max)
Max = num[i];
}
if (Max == Min) return 0;

int bucketGap = (Max - Min)/num.size() + 1; // 桶的间隔是关键
int bucketLen = (Max - Min)/bucketGap + 1; // 举个 1,2,3的例子就知道了
vector<int> MinMax(2, INT_MAX);
MinMax[1] = INT_MIN;
vector<vector<int> > bucket(bucketLen, MinMax);

for (int i = 0; i < num.size(); i++)
{
int ind = (num[i] - Min)/bucketGap;
if (num[i] < bucket[ind][0])
bucket[ind][0] = num[i];
if (num[i] > bucket[ind][1])
bucket[ind][1] = num[i];
}

int first = bucket[0][1], second;
for (int i = 1; i < bucketLen; i++)
{
if (bucket[i][0] == INT_MAX) continue;
second = bucket[i][0];
int tmpmax = second - first;
ans = tmpmax > ans ? tmpmax : ans;
first = bucket[i][1];
}

return ans;
}
};


View Code

最后附上官网的解法说明:

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: