首页 > 代码库 > [leetcode]Maximum Gap
[leetcode]Maximum Gap
用分桶的做法,思路参考自网友,很精妙。
class Solution {public: int maximumGap(vector<int> &num) { int size = num.size(); if (size < 2) { return 0; } int maxVal = *max_element(num.begin(), num.end()); int minVal = *min_element(num.begin(), num.end()); int gap = (maxVal - minVal - 1) / (size - 1) + 1; // ceiling function int bucketSize = (maxVal - minVal) / gap; vector<int> minBucket(bucketSize, INT_MAX); vector<int> maxBucket(bucketSize, INT_MIN); for (int i = 0; i < size; i++) { if (num[i] == minVal || num[i] == maxVal) { continue; } int idx = (num[i] - minVal) / gap; minBucket[idx] = min(minBucket[idx], num[i]); maxBucket[idx] = max(maxBucket[idx], num[i]); } int maxGap = INT_MIN; int prev = minVal; for (int i = 0; i < bucketSize; i++) { if (minBucket[i] != INT_MAX) { maxGap = max(maxGap, minBucket[i] - prev); prev = maxBucket[i]; } } maxGap = max(maxGap, maxVal - prev); return maxGap; }};
[leetcode]Maximum Gap
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。