[LeetCode]164. Maximum Gap
来源:互联网 发布:arduino摄像头编程 编辑:程序博客网 时间:2024/05/14 19:05
原题链接:https://leetcode.com/problems/maximum-gap/
这道题如果是O(nlgn)方法肯定很简单,排序后找最大gap就行了。但如果要求O(n)时间完成的话,难度就大大加大了。所以我们用桶排序的方法来做这道题。 有关桶排序的简介,大家可以参考维基-桶排序。我们来介绍一下桶排序的应用,桶排序就是将一定范围的值全部丢到同一个桶里。所以我们只要合理安排桶的个数,让最大的差异出现的桶与桶之间即可。假设输入的数组中的个数是n,范围从a~b。则我们会发先最大的gap一定会大于等于ceiling(b-a)/(n-1),因为如果数组是等差数列,数与数之间的差异是ceiling(b-a)/(n-1),所以最大gap不可能比这个还小。所以我们假设让桶的容量变成ceiling(b-a)/(n-1),那最大差异一定发生的桶之间。所以我们只要设置(b-a)/[ceiling(b-a)/(n-1)]+1个桶即可。然后就是桶之间的比较我们只需比较上一个桶的最大值和当前桶的最小值即可。所以桶里只需维护一个最大值和一个最小值。时间复杂度是O(n),空间复杂度是O(n)
代码如下:
public class Solution { public class bucket { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; } public int maximumGap(int[] nums) { if(nums.length <= 1) return 0; int len = nums.length; bucket[] buckets = new bucket[len]; int min = nums[0]; int max = nums[0]; for(int i = 0;i<len;i++) { if(nums[i]<min) min = nums[i]; if(nums[i]>max) max = nums[i]; } int seg = (int)Math.ceil((double)(max-min)/(len-1)); if(seg == 0) return 0; for(int i = 0;i<len;i++) { int t = nums[i]; int k = (t-min)/seg; if(buckets[k]==null) buckets[k] = new bucket(); if(buckets[k].max<t) buckets[k].max = t; if(buckets[k].min>t) buckets[k].min = t; } int gap = 0; int preMax = max; for(int i = 0;i<buckets.length;i++) { if(buckets[i]!=null) { gap = Math.max(gap,buckets[i].min-preMax); preMax = buckets[i].max; } } return gap; }}这道题方法很巧妙,思路也就是想着如何把数据分组开始。如果遇到类似的变种题没思路,面试官提示用到桶排序,大家一定要知道该怎么往下想。
0 0
- [LeetCode]164.Maximum Gap
- [LeetCode]164. Maximum Gap
- LeetCode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- leetcode.164. Maximum Gap
- [LeetCode] 164. Maximum Gap
- [leetcode] 164. Maximum Gap
- LeetCode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- 164. Maximum Gap [leetcode]
- leetcode 164. Maximum Gap
- LeetCode 164. Maximum Gap
- LCP164 LeetCode 164. Maximum Gap
- [LeetCode]problem 164. Maximum Gap
- [leetcode] 164.Maximum Gap
- [leetcode] 164. Maximum Gap 解题报告
- LeetCode 164. Maximum Gap(最大空隙)
- 基数排序 leetcode oj 164. Maximum Gap
- 面试笔试杂项积累-leetcode 141-145
- python的正则表达式 re
- fibonacci数列 取模
- N-Queens II 经典问题:8皇后问题 题解
- 具备白名单、黑名单的Filter基类扩展
- [LeetCode]164. Maximum Gap
- jQuery13(相对元素的练习)
- 如何成为一个技术大牛
- 机器学习基石笔记-感知机
- linux下fdisk建盘
- N-Queens 题解
- [Algorithm]Maze Prim算法与A*寻路算法(中)
- poj 2983 Is the Information Reliable?(差分约束)
- java的几种对象(PO,VO,DAO,BO,POJO)解释