L703. Kth Largest Element in a Stream
用k size minheap
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.nums = nums
self.k = k
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
def add(self, val):
"""
:type val: int
:rtype: int
"""
if len(self.nums) < self.k:
heapq.heappush(self.nums, val)
else:
if val > self.nums[0]:
#heapq.heapreplace(self.nums, val)
heapq.heappop(self.nums)
heapq.heappush(self.nums, val)
return self.nums[0]
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.nums = nums
self.k = k
heapq.heapify(self.nums)
while len(self.nums) > k:
heapq.heappop(self.nums)
def add(self, val):
"""
:type val: int
:rtype: int
"""
if len(self.nums) < self.k:
heapq.heappush(self.nums, val)
else:
if val > self.nums[0]:
heapq.heapreplace(self.nums, val)
return self.nums[0]
Last updated
Was this helpful?