Description
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your Kth Largest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Solution
Use maxHeap to find top K
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
if len(nums)<k:
self.heap=nums
self.k=None
else:
nums.sort(reverse=True)
self.heap=nums[:k-1]
self.k=nums[k-1]
heapq.heapify(self.data_1)
def add(self, val):
"""
:type val: int
:rtype: int
"""
if val <= self.k:
return self.k
else:
heapq.heappush(self.heap, val)
self.k=heapq.heappop(self.heap)
return self.k
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
网友评论