February——703. Summary of the K-th largest element in the data stream & heap and the use of API

Before talking about this topic today, let's talk about a data structure: heap. The heap is divided into the largest heap and the smallest heap. The maximum heap is when the value of the parent node is always greater than or equal to the value of any child node. The value of the parent node is always less than or waits for the value of any child node of the user to be the minimum heap. In fact, to put it bluntly, it is a complete binary tree data structure. As shown in the figure below, the left is the largest heap, and the right is the smallest heap .

The application of the maximum heap and the minimum heap is similar to the priority queue, and a maximum or minimum value can be popped every time. Of course, there is a corresponding API in python. Next, the method of heap API is roughly explained:

#导入堆
import heapq

#将list转化堆
heapq.heapify(x)
#将item添加到堆中,保持堆的不变性
heapq.heappush(heap, item)
#弹出并返回heap中的最小元素
heapq.heappop(heap)
#将 item 放入堆中,然后弹出并返回 heap 的最小元素。该组合操作比先调用  heappush() 再调用 heappop() 运行起来更有效率。
heapq.heappushpop(heap, item)
#弹出并返回 heap 中最小的一项,同时推入新的 item。 堆的大小不变
heapq.heapreplace(heap, item)

#返回前n个最大或者最小的元素
heapq.nlargest(n, iterable, key=None)
heapq.nsmallest(n, iterable, key=None)
#将多个已排序的输入合并为一个已排序的输出
heapq.merge(*iterables, key=None, reverse=False)

 Analysis: This question seeks the Kth largest element, then we can construct a minimum heap, the size of this heap is kept at k elements, and the element at the top of the heap happens to be the Kth largest element.

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
       
        #维护一个最小堆,堆顶的元素是最小的
        self.k = k
        self.heap = nums   
        heapq.heapify(self.heap)
        #堆顶的元素不断弹出,维护一个含有K个元素大小的最小堆
        while len(self.heap) > k:
            heapq.heappop(self.heap)


    def add(self, val: int) -> int:
        #将元素添加到最小堆中去
        heapq.heappush(self.heap,val)
        #添加之后的元素如果大于k,那就弹出堆顶元素
        if len(self.heap)>self.k:
            heapq.heappop(self.heap)

        #返回堆顶元素
        return self.heap[0]



# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

Summary: Only the minimum heap is implemented in the Python API, but the maximum heap is not implemented.

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/113842674