[Leetcode新题] Maximum Gap
来源:互联网 发布:制作微课都用哪些软件 编辑:程序博客网 时间:2024/06/05 04:39
题目: https://oj.leetcode.com/problems/maximum-gap/
这一题用到了鸽笼原理,是非常经典的一道题。因为代码注释的非常详细,写的逻辑也比较清楚,复习的时候应该不会看不懂。
class Solution {public: int maximumGap(vector<int> &num) { int size = num.size(), max_gap = 0; int max_total, min_total; int range, bucket_size; int last_max; if (size < 2) { return 0; } // 第一步,先得到最大值和最小值 max_total = min_total = num[0]; for (int i=1; i<size; ++i) { max_total = max(max_total, num[i]); min_total = min(min_total, num[i]); } // 第二步,根据最大值最小值划分size - 1个桶 range = max_total - min_total + 1; bucket_size = range / (size - 1); if (range % (size - 1) != 0) { bucket_size++; } { vector<vector<int> > bucket(size - 1, vector<int>(0)); vector<int> bucket_max(size - 1), bucket_min(size - 1); // 第三步,把除了最大值最小值之外的数据放到size - 1个桶里 // ps :数据有size - 2个,根据鸽笼原理,应该至少有一个桶是空的, // 因此,最大的gap必然不会出现在桶内元素之间 for (int i=0; i<size; ++i) { if (num[i] != max_total && num[i] != min_total) { bucket[(num[i] - min_total) / bucket_size].push_back(num[i]); } } // 第四步,计算每个桶内的最大值最小值,如果是空桶,最大值最小值都为-1 for (int i=0; i<size-1; ++i) { if (bucket[i].size()) { bucket_max[i] = bucket_min[i] = bucket[i][0]; for (int j=1; j<bucket[i].size(); ++j) { bucket_max[i] = max(bucket_max[i], bucket[i][j]); bucket_min[i] = min(bucket_min[i], bucket[i][j]); } } else { bucket_max[i] = bucket_min[i] = -1; } } // 第五步,计算每个桶的最大值和下一个桶最小值之间的gap,更新max_gap last_max = min_total; if (bucket_min[0] != -1) { max_gap = max(bucket_min[0] - min_total, 0); last_max = bucket_max[0]; } for (int i=1; i<size-1; ++i) { if (bucket_min[i] != -1) { max_gap = max(max_gap, bucket_min[i] - last_max); last_max = bucket_max[i]; } } max_gap = max(max_gap, max_total - last_max); return max_gap; } }};
0 0
- [Leetcode新题] Maximum Gap
- leetcode-Maximum Gap
- [LeetCode] Maximum Gap
- LeetCode Maximum Gap
- [leetCode] Maximum Gap
- leetcode 155: Maximum Gap
- LeetCode(164) Maximum Gap
- [LeetCode] Maximum Gap
- [leetcode 164] Maximum Gap
- [leetcode]Maximum Gap
- LeetCode - Maximum Gap 题解
- Maximum Gap|leetcode题解
- LeetCode[Sort]: Maximum Gap
- [LeetCode] Maximum Gap
- leetcode maximum gap
- [LeetCode]Maximum Gap
- LeetCode OJ Maximum Gap
- LeetCode Maximum Gap
- leedcode做题总结,动态规划II(Maximum Subarray,Maximum Product Subarray)
- leetcode-letter combination of a phone number
- leedcode做题总结, 题目Find Minimum in Rotated Sorted Array I/II
- 用openfire+strophe搭建WEB IM平台
- 验证Hu矩的旋转不变性
- [Leetcode新题] Maximum Gap
- Why need to train your code sense?
- dnf在拉留存上值得学习的地方
- 谈谈比特币,谈谈云
- OJ刷题之《复制字符串》
- in excess of seven hundred nm
- 【将金令】1.8早评:美元撞上纪要,警惕变盘
- D3学习笔记
- 美术教学中新的创作理念融合的方法