164. Maximum Gap【H】【80】【桶排序】【VIP】
来源:互联网 发布:数据库应用系统的构成 编辑:程序博客网 时间:2024/05/22 16:42
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.
Subscribe to see which companies asked this question
注释掉的方法肯定是比较流氓的了。。
重点在于桶排序
这个思想还是很好用的
利用桶排序思想:
假设有N个元素数组array,最大值为Max,最小值为Min。
那么最大差值不会大于ceiling[(Maz - Min) / (N - 1)]。
令bucket(桶)的大小len = ceiling[(Maz - Min) / (N - 1)],则最多会有(Max - Min) / len + 1个桶
对于数组中的任意整数K,很容易通过算式index = (K - Min) / len找出其桶的位置,然后维护每一个桶的最大值和最小值。
由于同一个桶内的元素之间的差值至多为len - 1,因此最终答案不会从同一个桶中选择。
对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。
class Solution(object): def maximumGap(self, nums): if len(nums) < 2: return 0 a = min(nums) b = max(nums) if a == b: return 0 size = math.ceil((b - a) / (len(nums) + 0.0) ) #print size if size == 0: size = 1 if size != int(size): size = int(size) + 1 else: size = int(size) #print a,b,size,len(nums) bucketMin = [sys.maxint] * (len(nums) + 1) bucketMax = [0] * (len(nums) + 1) for i in nums: index = (i - a) / size #print index,i,size bucketMin[index] = min(bucketMin[index],i) bucketMax[index] = max(bucketMax[index],i) prv = bucketMax[0] res = 0 for i in xrange(len(nums)): if bucketMin[i] == sys.maxint: continue res = max(bucketMin[i] - prv,res) prv = bucketMax[i] #print bucketMax,bucketMin #print res return res ''' nums.sort() i = 0 res = 0 while i < len(nums) - 1: res = max(res,nums[i+1] - nums[i]) i += 1 return res '''
0 0
- 164. Maximum Gap【H】【80】【桶排序】【VIP】
- 【桶排序】MAXIMUM GAP
- 【leetcode 桶排序】Maximum Gap
- [leetcode][桶排序] Maximum Gap
- 由Maximum Gap,谈桶排序,基数排序和计数排序
- [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
- STL学习之路
- Python闲谈(一)mgrid慢放
- 2016百度之星热身赛 1002
- jQuery 事件 - mousedown() 方法
- 《安卓笔记》——Parcelable接口
- 164. Maximum Gap【H】【80】【桶排序】【VIP】
- 位运算
- Can not find the tag library descriptor for "http://Java.sun.com/jsp/jstl/core"
- 2012年第三届蓝桥杯C/C++程序设计本科B组决赛 数据压缩(代码填空)
- python string.atof( )函数
- K最近邻(KNN,k-Nearest Neighbor)准确理解
- jboss启动超时问题
- 【设计模式】:23种设计模式
- [Objective-C]关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)