Skip to content

Commit 0a53804

Browse files
fix bug
1 parent 09230bf commit 0a53804

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

Target Offer/最小的k个数.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,21 @@ def GetLeastNumbers(self, tinput, k):
5757
if len(output) < k:
5858
output.append(number)
5959
else:
60-
output = heapq.nsmallest(k, output)
61-
if number >= output[-1]:
60+
# 构造最小堆, 不推荐
61+
# output = heapq.nsmallest(k, output)
62+
# if number >= output[-1]:
63+
# continue
64+
# else:
65+
# output[-1] = number
66+
# 构造最大堆, 推荐
67+
output = heapq.nlargest(k, output)
68+
if number >= output[0]:
6269
continue
6370
else:
64-
output[-1] = number
65-
return output
71+
output[0] = number
72+
return output[::-1] # 最小堆用 return output
6673
tinput = [4,5,1,6,2,7,3,8]
6774
s = Solution()
6875
print(s.GetLeastNumbers_Solution(tinput, 4))
6976
print(s.GetLeastNumbers(tinput, 4))
70-
print(s.GetLeastNumbers(tinput, 5))
77+
print(s.GetLeastNumbers(tinput, 5))

0 commit comments

Comments
 (0)