mirror of
https://github.com/devenperez/leetcode.git
synced 2026-06-15 09:57:09 +00:00
18 lines
488 B
Python
18 lines
488 B
Python
import heapq
|
|
|
|
class Solution:
|
|
def findKthLargest(self, nums: List[int], k: int) -> int:
|
|
heap = nums[:k]
|
|
|
|
# Heapify (min) the first k elements
|
|
heapq.heapify(heap)
|
|
|
|
# iterate over k+1...n - O(n) times
|
|
# - if larger than min in heap, replace min - O(log k)
|
|
# - else do nothing
|
|
for num in nums:
|
|
if num > heap[0]:
|
|
heapq.heapreplace(heap, num)
|
|
|
|
# return min in heap
|
|
return heap[0] |