leetcode 164. Maximum Gap

链接地址:leetcode链接

思路:使用基数排序可以使时间复杂度为O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import math
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums)<2:return 0
self.radixSort(nums)
maxgap = 0
for i in range(1,len(nums)):
if nums[i]-nums[i-1]>maxgap:
maxgap = nums[i]-nums[i-1]
return maxgap

def radixSort(self,nums,base=10):
k = int(math.ceil(math.log(max(nums)+1,base)))
for i in range(1,k+1):
bucket = [[] for _ in range(base)]
for num in nums:
bucket[num//(base**(i-1))%base].append(num)
del nums[:]#del nums[:]表示删除数组内的整数,nums变量还存在为[];del nums表示删除整个数组,nums变量不存在了
for each in bucket:
nums.extend(each)