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

Commit748f892

Browse files
committed
Update 0215. 数组中的第K个最大元素.md
1 parentee45813 commit748f892

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

‎Solutions/0215. 数组中的第K个最大元素.md‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ class Solution:
162162

163163
###思路 3:借用标准库(不建议)
164164

165-
提交代码中的最快代码是调用了`Python``heapq` 库,或者`sort` 方法。这种做法适合在打算法竞赛的时候节省时间,日常练习不建议不建议这样做。
165+
提交代码中的最快代码是调用了`Python``sort` 方法。这种做法适合在打算法竞赛的时候节省时间,日常练习不建议不建议这样做。
166166

167167
###思路 3:代码
168168

@@ -173,22 +173,37 @@ class Solution:
173173
return nums[len(nums)- k]
174174
```
175175

176+
###思路 3:复杂度分析
177+
178+
-**时间复杂度**:$O(n \times \log_2n)$。
179+
-**空间复杂度**:$O(1)$。
180+
181+
###思路 4:优先队列
182+
183+
1. 遍历数组元素,对于挡圈元素`num`
184+
1. 如果优先队列中的元素个数小于`k` 个,则将当前元素`num` 放入优先队列中。
185+
2. 如果优先队列中的元素个数大于等于`k` 个,并且当前元素`num` 大于优先队列的队头元素,则弹出队头元素,并将当前元素`num` 插入到优先队列中。
186+
2. 遍历完,此时优先队列的队头元素就是第K个最大元素,将其弹出并返回即可。
187+
188+
这里我们借助了 Python 中的`heapq` 模块实现优先队列算法,这一步也可以通过手写堆的方式实现优先队列。
189+
190+
###思路 4:代码
191+
176192
```Python
177193
import heapq
178194
classSolution:
179195
deffindKthLargest(self,nums: List[int],k:int) ->int:
180196
res= []
181-
fornin nums:
197+
fornumin nums:
182198
iflen(res)< k:
183-
heapq.heappush(res,n)
184-
elifn> res[0]:
199+
heapq.heappush(res,num)
200+
elifnum> res[0]:
185201
heapq.heappop(res)
186-
heapq.heappush(res,n)
202+
heapq.heappush(res,num)
187203
return heapq.heappop(res)
188204
```
189205

190-
###思路 3:复杂度分析
191-
192-
-**时间复杂度**:$O(n \times \log_2n)$。
193-
-**空间复杂度**:$O(1)$。
206+
###思路 4:复杂度分析
194207

208+
-**时间复杂度**:$O(n \times \log_2k)$。
209+
-**空间复杂度**:$O(k)$。

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp