Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
求一列数的第K大,优先队列打卡题


 1 #703
 2 #Runtime: 95 ms (Beats 80.5%)
 3 #Memory: 17.9 MB (Beats 17.87%)
 4 
 5 class KthLargest(object):
 6 
 7     def __init__(self, k, nums):
 8         """
 9         :type k: int
10         :type nums: List[int]
11         """
12         self.nums = nums
13         self.K = k
14         heapify(self.nums)
15         while len(self.nums) > self.K:
16             heappop(self.nums)
17 
18     def add(self, val):
19         """
20         :type val: int
21         :rtype: int
22         """
23         if len(self.nums) < self.K:
24             heappush(self.nums, val)
25         elif val > self.nums[0]:
26             heapreplace(self.nums, val)
27         return self.nums[0]
28         
29 
30 
31 # Your KthLargest object will be instantiated and called as such:
32 # obj = KthLargest(k, nums)
33 # param_1 = obj.add(val)

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理