[leetcode] Maximum Gap
来源:互联网 发布:iphone视频截图软件 编辑:程序博客网 时间:2024/06/07 01:14
From : https://leetcode.com/problems/maximum-gap/
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.
思路 :用桶排序原理,将n个数放入n个桶中,记录每个桶中的最大和最小值。
如果n个数分别在n个桶中,那么后一桶的最大(同时也是最小)与前一桶的最小(同时也是最大)之差的最大就是maxGap; 否则,如果n个数不全在n个桶中,那么必然有空桶,空桶后一个的最小和前一个的最大的差必然比桶的长度达,那么后桶最小和前桶最大之差的最大仍然是maxGap。
综上所述,取 max{buckets[0].max-buckets[0].min, buckets[n-1].max-buckets[n-1].min, max {buckets[i].min-buckets.max}}, 即buckets[0].max-buckets[0].min , buckets[n-1].max-buckets[n-1].min 和 max {buckets[i].min-buckets.max}的最大值。
public class Solution { class Bucket { // if min < 1, the bucket is empty int min = -1; int max; } public int maximumGap(int[] nums) { if(nums.length < 2) { return 0; } int len = nums.length; int gmax = nums[0], gmin = gmax; for(int i=1; i<len; ++i) { int c = nums[i]; if(c < gmin) { gmin = c; } else if(c > gmax) { gmax = c; } } int size = (int) Math.ceil( (double)(gmax - gmin + 1) / (double)len ); Bucket[] buckets = new Bucket[len]; // len buckets for(int i=0; i<len; ++i) { buckets[i] = new Bucket(); } for(int num : nums) { Bucket bucket = buckets[(num-gmin)/size]; if(bucket.min < 0) { // empty bucket bucket.min = bucket.max = num; } else { if(num < bucket.min) { bucket.min = num; } else if(num > bucket.max) { bucket.max = num; } } } int min = buckets[0].min, max=min, maxGap = buckets[0].max-min; for(Bucket b : buckets) { if(b.min < 0) { continue; } min = b.min; if(min - max > maxGap) { maxGap = min-max; } max = b.max; } return gmax-min > maxGap ? gmax-min : maxGap; }}
- 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
- FZU 1752 A^B mod C
- 稳定排序和不稳定排序
- GIT
- C语言编程入门——综合练习(一)
- andoid中的通知
- [leetcode] Maximum Gap
- C语言:线性顺序结构(数组)的插入,删除
- 第三周遗忘总结
- 音频播放,gif图的播放,毛玻璃效果 UISlider,UIStepper,UISegmentedControl
- “哎哟!蛮吊的” 之 Android BroadCastReceiver详解
- 12558 - Egyptian Fractions (HARD version)(IDA*算法)
- C++封装互斥量和条件变量
- VNC Viewer连接成功后闪退的解决办法
- HDU 4508 湫湫系列故事——减肥记I