164. 最大间距
程序员文章站
2022-04-04 10:06:06
...
链接:164. 最大间距
题解:https://leetcode-cn.com/problems/maximum-gap/solution/zui-da-jian-ju-by-leetcode-solution/
class Solution {
public:
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2) {
return 0;
}
int minVal = *min_element(nums.begin(), nums.end());
int maxVal = *max_element(nums.begin(), nums.end());
int d = max(1, (maxVal - minVal) / (n - 1)); // 两个桶之间的间隙
int bucketSize = (maxVal - minVal) / d + 1; // 桶的个数
vector<pair<int, int>> bucket(bucketSize, {-1, -1}); // 存储 (桶内最小值,桶内最大值) 对,(-1, -1) 表示该桶是空的
for (int i = 0; i < n; i++) {
// 需要放入桶的下标
int idx = (nums[i] - minVal) / d;
// 桶之前没有元素
if (bucket[idx].first == -1) {
bucket[idx].first = bucket[idx].second = nums[i];
} else {
bucket[idx].first = min(bucket[idx].first, nums[i]);
bucket[idx].second = max(bucket[idx].second, nums[i]);
}
}
int ret = 0;
int prev = -1;
// 比较相邻两个有值的桶
for (int i = 0; i < bucketSize; i++) {
if (bucket[i].first == -1) continue;
if (prev != -1) {
ret = max(ret, bucket[i].first - bucket[prev].second);
}
prev = i;
}
return ret;
}
};