Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0a53804

Browse files
fix bug
1 parent09230bf commit0a53804

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
iflen(output)<k:
5858
output.append(number)
5959
else:
60-
output=heapq.nsmallest(k,output)
61-
ifnumber>=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+
ifnumber>=output[0]:
6269
continue
6370
else:
64-
output[-1]=number
65-
returnoutput
71+
output[0]=number
72+
returnoutput[::-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)

[8]ページ先頭

©2009-2025 Movatter.jp