[LeetCode]Maximum Gap
来源:互联网 发布:靠谱的美国代购淘宝店 编辑:程序博客网 时间:2024/05/29 20:05
https://leetcode.com/problems/maximum-gap/
找出乱序数组排序之后相邻的最大差值
找gap的时候想到桶,桶排序思想
这里建桶有trick:保证bucket比最小gap可能值还小,那这样只需要桶间比较,不需要桶内比较。
最大gap不会比ceiling[(max - min ) / (N - 1)]更小。因为即便(max - min ) / (N - 1)结果是小数,最大gap也不会是向下取整的结果,gap肯定有比(max - min ) / (N - 1)大的也有比他小的。
如果两个数的差值大于等于bucket,那么这两个数一定不会在一个桶里面!!因为桶的index是(val - min) / bucket!!!
public class Solution { public int maximumGap(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int i : nums) { max = Math.max(max, i); min = Math.min(min, i); } // 保证bucket小于可能的最小gap即可。 // 当(max - min) / (nums.length - 1)为零时,最坏为等差数列桶内差值为结果, // 但此时桶间差值亦为结果,故下解成立。 int bucket = (int) Math.ceil((double) (max - min) / (nums.length - 1)); // min&max都不存,避免bucket为零的除法 int[] maxArr = new int[nums.length - 1]; int[] minArr = new int[nums.length - 1]; Arrays.fill(maxArr, Integer.MIN_VALUE); Arrays.fill(minArr, Integer.MAX_VALUE); for (int i : nums) { if (i == max || i == min) { continue; } int index = (i - min) / bucket; maxArr[index] = Math.max(maxArr[index], i); minArr[index] = Math.min(minArr[index], i); } int pre = min; int res = Integer.MIN_VALUE; for (int i = 0; i < nums.length - 1; i++) { if (maxArr[i] == Integer.MIN_VALUE || minArr[i] == Integer.MAX_VALUE) { continue; } res = Math.max(res, minArr[i] - pre); pre = maxArr[i]; } return Math.max(res, max - pre); }}
0 0
- 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
- 【leetcode】 Maximum Gap
- 第十四周项目3-是否二叉排序树?
- 音频噪声抑制(4):普通最小均方误差(LMS)算法
- C语言OJ项目参考(2568) 字符串逆序输出
- 经典选项卡问题
- 微信小程序上传图片(附后端代码)
- [LeetCode]Maximum Gap
- 第十四周项目1-(2)验证分块查找算法
- mantisbt 测试
- HDFS 简介
- python 爬虫‘Max retries exceeded with url’错误
- Android gridview实现简单的九宫格布局
- Android Studio插件之GsonFormat
- iOS——导航栏透明,上滑变蓝色
- Notepad 格式化XML