1. 程式人生 > 其它 >數塔取數問題(你一定可以看懂)

數塔取數問題(你一定可以看懂)

技術標籤:leetcode

2021-02-11 Leetcode每日刷題

題目

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.
Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Returns the element representing the kth largest element in the stream.

Example 1:

Input
[“KthLargest”, “add”, “add”, “add”, “add”, “add”]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]

Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);

kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8

Constraints:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
At most 104 calls will be made to add. It is guaranteed that there will be at least k elements in the array when you search for the kth

element.

我的思路
沒有思路。每次insert之後排序並輸出第k個數字可以,但是會超時。不過可以手動排序,初始化後進行排序,接下來每次add使用insert排到合適的位置,但是還是太麻煩了。

參考思路
使用堆排序。之前並沒有學過堆排序。可以參考這位的部落格寫的很詳細。
https://www.cnblogs.com/wangchaowei/p/8288216.html
總之,使用heap每次插入一個元素需要從下到上從子節點到根節點排一遍序,每次刪除一個元素需要從上到下從根節點到子節點排一遍。如果max-heap(min-heap)的長度為k,那麼根節點就是heap中第k小(大)的數字。

那麼這道題就可以先把整個陣列變成小根堆,並保留前k個元素。每次add時進行heappush()和heappop(),兩個操作時間複雜度均為log(k)。

程式碼:

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.nums = nums
        heapq.heapify(self.nums)
        while len(self.nums)>self.k:
            heapq.heappop(self.nums)

    def add(self, val: int) -> int:
        heapq.heappush(self.nums,val)
        while len(self.nums) > self.k:
            heapq.heappop(self.nums)
        return self.nums[0]



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

提交結果
在這裡插入圖片描述
總結一下,堆的資料結構要好好學習,經常複習。前K個元素也在面試題中經常出現,需要再多找幾道題鞏固一下。對這道題本身來說,自己編寫幾種排序方法也是ok的,可以多寫幾遍當作複習不同的排序方法了。
最後祝所有人除夕快樂!!!我要去繼續寫作業了。