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找出其桶的位置,然后维护每一个桶的最大值和最小值。
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
'''