mirror of
https://github.com/devenperez/leetcode.git
synced 2026-06-15 09:57:09 +00:00
Time: N/A (0%), Space: N/A (0%) - LeetHub
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
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]
|
||||
Reference in New Issue
Block a user