Skip to content

Commit 8c1d65f

Browse files
桶排序
1 parent 4154574 commit 8c1d65f

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

每日一题/164最大间距.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
'''
2+
Descripttion: 164. 最大间距
3+
version: 1
4+
Author: Jason
5+
Date: 2020-11-26 09:51:12
6+
LastEditors: Jason
7+
LastEditTime: 2020-11-26 22:51:10
8+
'''
9+
10+
11+
import random
12+
from typing import List
13+
14+
15+
def GenerateRandomList(number, size):
16+
temp = list()
17+
random_legth = random.randint(0, size)
18+
current_length = 0
19+
while current_length < random_legth:
20+
temp.append(random.randint(1, number))
21+
current_length += 1
22+
return temp
23+
24+
25+
class Solution:
26+
def maximumGap(self, nums: List[int]) -> int:
27+
length = len(nums)
28+
if length < 2:
29+
return 0
30+
max_num = max(nums)
31+
min_num = min(nums)
32+
# 每个桶的长度 (max-min) / (len(nums) - 1)
33+
each_bucket_length = max(1, (max_num - min_num) // (length - 1))
34+
# 桶的数量
35+
buckets_nums = (max_num - min_num) // each_bucket_length + 1
36+
# 创建桶,并将数字放置到相应桶内
37+
buckets = [[] for _ in range(buckets_nums)]
38+
for i in range(length):
39+
buckets[(nums[i] - min_num) // each_bucket_length].append(nums[i])
40+
pre_max = None
41+
res = 0
42+
for i in range(buckets_nums):
43+
if buckets[i] and pre_max:
44+
res = max(res, min(buckets[i]) - pre_max)
45+
46+
if buckets[i]:
47+
pre_max = max(buckets[i])
48+
return res
49+
50+
def maximumGap2(self, nums: List[int]) -> int:
51+
length = len(nums)
52+
if length < 2:
53+
return 0
54+
nums.sort()
55+
res = float("-inf")
56+
for i in range(length - 1):
57+
temp = nums[i + 1] - nums[i]
58+
if temp > res:
59+
res = temp
60+
return res
61+
62+
63+
s = Solution()
64+
for _ in range(100):
65+
li = GenerateRandomList(100, 40)
66+
res1 = s.maximumGap(li[::])
67+
res2 = s.maximumGap2(li[::])
68+
if res1 != res2:
69+
print("wrong")
70+
print(li)
71+
print("Done")

0 commit comments

Comments
 (0)