Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # O(k) + (n-k)logK = nlogk
- # O(k)
- class Solution:
- def findKthLargest(self, nums: List[int], k: int) -> int:
- # convert this problem of converting to find the minium among
- # k largest element in a list
- heap = [x for x in nums[:k]]
- heapq.heapify(heap)
- # Wrong
- # for i in range(k, len(nums)-1):
- # Right
- for i in range(k, len(nums)):
- # sinve we are trying to keep the k-largest numbers in the heap
- # we will add any incoming element that is the larger than the min
- # of the heap. Because our goal is to have as many large elements
- # in the heap
- if heap and heap[0] < nums[i]:
- heapq.heappop(heap)
- heapq.heappush(heap, nums[i])
- return heap[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement