[LeetCode164] Maximum Gap
来源:互联网 发布:供应商考核表数据 编辑:程序博客网 时间:2024/06/06 07:49
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.
public int maximumGap(int[] nums) { if(nums.length <2) return 0; if(nums.length ==2) { return Math.abs(nums[0]-nums[1]); } int maxValue = nums[0]; int minValue = nums[0]; for(int i=1; i<nums.length; i++){ maxValue = (maxValue> nums[i])? maxValue:nums[i]; minValue = (minValue< nums[i])? minValue:nums[i]; } int avGap = (maxValue-minValue) / (nums.length-1); int bucketCount = 0; if(avGap == 0){ return maxValue-minValue; }else { bucketCount = (maxValue-minValue) / avGap; } //<min,max>, initiate map List<Node> bucketMap = new ArrayList<>(); for(int i=0;i<=bucketCount;i++){ bucketMap.add(new Node(Integer.MAX_VALUE, Integer.MIN_VALUE)); } //every bucket min&max for(int i=0;i<nums.length;i++){ int index = (nums[i]-minValue)/avGap; int tempMax = (bucketMap.get(index).max<nums[i])?nums[i]:bucketMap.get(index).max; int tempMin = (bucketMap.get(index).min>nums[i])?nums[i]:bucketMap.get(index).min; bucketMap.get(index).setValue(tempMin, tempMax);// bucketMap.add(index, new Node(tempMin, tempMax)); } //find maximum int maxGap = 0; int maxLeft = bucketMap.get(0).max; for(int i=1;i<=bucketCount;i++){ Node n1 = bucketMap.get(i); if(n1.min!=Integer.MAX_VALUE){ maxGap = Math.max(maxGap, n1.min-maxLeft); maxLeft = n1.max; } } return maxGap; }class Node { int min; int max; public Node(int min, int max){ this.min = min; this.max = max; } public void setValue(int min,int max){ this.max = max; this.min = min; }}
0 0
- [LeetCode164] Maximum Gap
- [LeetCode164]Maximum Gap
- leetcode164~Maximum Gap
- leetcode164.Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- MAXIMUM GAP
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- Maximum Gap
- POJ 1961 Period kmp
- Spring入门
- 递归
- 华为OJ平台试题 —— 字符串:图片整理
- {System.InvalidOperationException: 无效操作。连接被关闭。
- [LeetCode164] Maximum Gap
- Poj 2826 An Easy Problem!
- 关于self点操作访问和下划线访问的区别
- android 编译共享ccache的缓存
- sqlserver 分组合并
- 树莓派上手实战之配置Samba服务器
- NYOJ_72 Financial Management
- [es6]Symbol.iterator 和 for of
- 面试问题