We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 09230bf commit 0a53804Copy full SHA for 0a53804
1 file changed
Target Offer/最小的k个数.py
@@ -57,14 +57,21 @@ def GetLeastNumbers(self, tinput, k):
57
if len(output) < k:
58
output.append(number)
59
else:
60
- output = heapq.nsmallest(k, output)
61
- if number >= output[-1]:
+ # 构造最小堆, 不推荐
+ # 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]:
69
continue
70
- output[-1] = number
- return output
71
+ output[0] = number
72
+ return output[::-1] # 最小堆用 return output
73
tinput = [4,5,1,6,2,7,3,8]
74
s = Solution()
75
print(s.GetLeastNumbers_Solution(tinput, 4))
76
print(s.GetLeastNumbers(tinput, 4))
-print(s.GetLeastNumbers(tinput, 5))
77
+print(s.GetLeastNumbers(tinput, 5))
0 commit comments