[LeetCode]Maximum Gap
来源:互联网 发布:以下哪种商品在淘宝网上可以出售 编辑:程序博客网 时间:2024/05/20 21:45
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
public class Solution {class Pair{int min;int max;Pair(int min,int max){this.min = min;this.max = max;}} public int maximumGap(int[] num) { if(num.length<=1) return 0; int mn = num[0],mx = num[0]; int len = num.length; for(int n:num){ mn = Math.min(mn, n); mx = Math.max(mx, n); } if(mn== mx) return 0; //桶间的间隔 int dist = (mx-mn)/len+1; //每个pair就是一个桶,用来存储映射到该桶的最大与最小数 Pair[]buck = new Pair[len]; for(int n:num){ //映射的桶下标 int index = (n-mn)/dist; if(buck[index]==null) { buck[index]= new Pair(n,n); continue; } Pair p = buck[index]; p.min = Math.min(n,p.min); p.max = Math.max(n,p.max); } int preMax = buck[0].max; int res = preMax-buck[0].min; for(int i=1;i<buck.length;i++){ Pair p = buck[i]; if(p==null) continue; res = Math.max(p.min-preMax, res); preMax = p.max; } return res; }}
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
- hdoj 1142 A Walk Through the Forest
- windows进程中的内存结构
- POJ-1003
- 笔记-vim编辑器
- 【模板】计算几何
- [LeetCode]Maximum Gap
- Linux使用模拟I2C
- ADuC7126学习(一):ADuC7126精密微控制器用keil4编写程序不能进入IRQ中断的问题
- 在cocos引擎中封装的集合类Vector
- 来京第十天
- RPC框架protobuf-rpc-pro 阻塞和非阻塞实例
- Learn Web.Crawling of Perl
- 选拨管理者的一个必要条件
- layout