Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- take a min heap and push the element if size of min heap is less than k.
- if min heap size is k so,kth maxium element will be at top of min heap
- so if current element is smaller than top of min heap then it will not
- contribute in kth maximum element else pop top element and push current
- element at top.
- every time kth maxiumum element will be at top if min heap size is k
- '''
- from heapq import heappush, heappop
- class Solution:
- def kthLargest(self, arr, k):
- heap = []
- res = []
- for num in arr:
- if len(heap) < k:
- heappush(heap, num)
- elif num > heap[0]:
- heappop(heap)
- heappush(heap, num)
- if len(heap) < k:
- res.append(-1)
- else:
- res.append(heap[0])
- return res
Advertisement
Add Comment
Please, Sign In to add comment