164. Maximum Gap
来源:互联网 发布:java文明5 编辑:程序博客网 时间:2024/06/06 03:50
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.
class Solution { public int maximumGap(int[] nums) { if (nums.length<2) return 0; int minNum = -1, maxNum = -1, n = nums.length; for (int i=0; i<n; ++i) { minNum = min(nums[i], minNum); maxNum = max(nums[i], maxNum); } if (maxNum==minNum) return 0; double average = (maxNum-minNum) * 1.0 / (n - 1); if (average==0) ++average; int[] localMin = new int[n]; int[] localMax = new int[n]; for (int i=0; i<n; ++i) { localMin[i] = -1; localMax[i] = -1; } for (int i=0; i<n; ++i) { int t = (int)((nums[i]-minNum) / average); localMin[t] = min(localMin[t], nums[i]); localMax[t] = max(localMax[t], nums[i]); } int ans = (int)average, left = 0, right = 1; while (left<n-1) { while (right<n && localMin[right]==-1) ++right; if (right>=n) break; ans = max(ans, localMin[right]-localMax[left]); left = right; ++right; } return ans; } private int min(int a, int b) { if (a==-1) return b; else if (b==-1) return a; else if (a<b) return a; else return b; } private int max(int a, int b) { if (a==-1) return b; else if (b==-1) return a; else if (a>b) return a; else return b; }}
阅读全文
0 0
- [LeetCode]164.Maximum Gap
- 164. Maximum Gap
- [LeetCode]164. Maximum Gap
- 164. Maximum Gap
- LeetCode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- 164. Maximum Gap
- leetcode.164. Maximum Gap
- 164. Maximum Gap
- 164. Maximum Gap
- 164. Maximum Gap
- [LeetCode] 164. Maximum Gap
- [leetcode] 164. Maximum Gap
- 164. Maximum Gap
- 164. Maximum Gap
- 164. Maximum Gap
- 164. Maximum Gap
- LeetCode 164. Maximum Gap
- 如何用Construct2制作简单HTML游戏
- UVA 11400 Lighting System Design 【贪心】【DP】
- flex布局-随鼠标滚动而滚动
- 全局scheduler的用法
- 把Actionbar 替换成 Toobar 的记录
- 164. Maximum Gap
- 感悟生活,再来聊聊拼多多
- android SENSOR_ACCELEROMETER 三轴加速度传感器
- 12星座程序员写代码
- 你的朋友国庆假期都去了哪里玩?微信大数据告诉你!最远的朋友圈签到竟然来自……
- Opencv 中 Mat中元素的值读取方法总结
- MD5
- OFBiz登录权限设置
- linux 学习系列-Linux 文件基本属性