File tree Expand file tree Collapse file tree 1 file changed +24
-9
lines changed Expand file tree Collapse file tree 1 file changed +24
-9
lines changed Original file line number Diff line number Diff line change @@ -162,7 +162,7 @@ class Solution:
162
162
163
163
### 思路 3:借用标准库(不建议)
164
164
165
- 提交代码中的最快代码是调用了 ` Python ` 的 ` heapq ` 库,或者 ` sort ` 方法。这种做法适合在打算法竞赛的时候节省时间,日常练习不建议不建议这样做。
165
+ 提交代码中的最快代码是调用了 ` Python ` 的 ` sort ` 方法。这种做法适合在打算法竞赛的时候节省时间,日常练习不建议不建议这样做。
166
166
167
167
### 思路 3:代码
168
168
@@ -173,22 +173,37 @@ class Solution:
173
173
return nums[len (nums) - k]
174
174
```
175
175
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
+
176
192
``` Python
177
193
import heapq
178
194
class Solution :
179
195
def findKthLargest (self , nums : List[int ], k : int ) -> int :
180
196
res = []
181
- for n in nums:
197
+ for num in nums:
182
198
if len (res) < k:
183
- heapq.heappush(res, n )
184
- elif n > res[0 ]:
199
+ heapq.heappush(res, num )
200
+ elif num > res[0 ]:
185
201
heapq.heappop(res)
186
- heapq.heappush(res, n )
202
+ heapq.heappush(res, num )
187
203
return heapq.heappop(res)
188
204
```
189
205
190
- ### 思路 3:复杂度分析
191
-
192
- - ** 时间复杂度** :$O(n \times \log_2n)$。
193
- - ** 空间复杂度** :$O(1)$。
206
+ ### 思路 4:复杂度分析
194
207
208
+ - ** 时间复杂度** :$O(n \times \log_2k)$。
209
+ - ** 空间复杂度** :$O(k)$。
You can’t perform that action at this time.
0 commit comments