美文网首页
2019-09-17 LC 703. Kth Largest E

2019-09-17 LC 703. Kth Largest E

作者: Mree111 | 来源:发表于2019-10-08 14:46 被阅读0次

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)

相关文章

网友评论

      本文标题:2019-09-17 LC 703. Kth Largest E

      本文链接:https://www.haomeiwen.com/subject/qqcfgqtx.html