215. Kth Largest Element in an Array
程序员文章站
2022-04-25 13:31:44
...
题目
求出数组中第k大的数字。
我的代码(维持一个k的列表)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
d=nums[:k]
d.sort()
for i in range(k,len(nums)):
if nums[i]>d[0]:
sign=False
for j in range(1,len(d)):
if nums[i]<=d[j]:
sign=True
d.insert(j,nums[i])
break
if not sign:
d.append(nums[i])
del d[0]
return d[0]
高效代码
使用堆队列的方法,提高了效率。
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heapq.heappop(heap)
推荐阅读
-
5. Kth Largest Element
-
Kth Largest Element in an Array Leetcode #215 题解[C++]
-
215. Kth Largest Element in an Array
-
LeetCode 215 Kth Largest Element in an Array
-
LeetCode 215. Kth Largest Element in an Array
-
LeetCode算法问题14 —— Kth Largest Element in an Array
-
215. Kth Largest Element in an Array(返回数组中第几大元素)(leetcode)
-
LeetCode 215 -- 数组中的第K个最大元素 ( Kth Largest Element in an Array ) ( C语言版 )
-
Kth Largest Element in an Array解题报告
-
215[Medium]:Kth Largest Element in an Array