题目描述
答案:
低效率版本
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.nums=nums
self.k=k
def add(self, val):
"""
:type val: int
:rtype: int
"""
self.nums.append(val)
self.nums.sort()
return self.nums[len(self.nums)-self.k]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
高效率版本
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.k = k
self.heap = nums
heapq.heapify(self.heap)
# 先把所有数据建立小根堆
# for n in nums:
# heapq.heappush(self.heap, n)
# 只保留top K个最小的
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
"""
:type val: int
:rtype: int
"""
# 如果元素数量小于K,直接返回堆顶元素
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
# 如果元素比堆顶的要小,则替换堆内元素,重新建堆
elif self.heap[0] < val:
heapq.heapreplace(self.heap, val)
return self.heap[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)