LeetCode C++ 703. Kth Largest Element in a Stream【Heap/Design】簡單
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 integerk
and the stream of integersnums
.int add(int val)
Returns the element representing thekth
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 toadd
. - It is guaranteed that there will be at least
k
elements in the array when you search for thekth
element.
題意:設計一個找到資料流中第 k
大元素的 KthLargest
類。注意是排序後的第 k
大元素,不是第 k
個不同的元素:
KthLargest(int k, int[] nums)
使用整數k
和整數流nums
初始化物件。int add(int val)
返回當前資料流中第k
大的元素。
解法 最小堆
題面寫得太差了,add(val)
的含義是:新增 val
到資料流中,然後返回當前資料流中第 k
大的元素。題目示例的解釋如下:
8 5 4 2, 返回第k = 3大的元素
add(3): 8 5 4 3 2, return 4,
add(5): 8 5 5 4 3 2, return 5,
add(10): 10 8 5 5 4 3 2, return 5,
add(9): 10 9 8 5 5 4 3 2, return 8,
add(4): 10 9 8 5 5 4 4 3 2, return 8
解法是維護一個 k
個元素的最小堆,如果最小堆不足 k
個元素,就直接將新元素壓入堆中;否則,如果資料流的新元素大於堆頂值,就彈出堆頂並將新元素入堆。於是第 k
大的元素一定在堆頂,我們返回堆頂元素即可。C++程式碼如下:
class KthLargest {
private:
priority_queue<int, vector<int>, greater<int>> pq; //維護一個k個元素的最小堆
int k;
public:
KthLargest(int k, vector<int>& nums) {
this->k = k;
for (const int &v : nums) {
if (pq.size() < k) pq.push(v);
else if (v > pq.top()) { //pq.size()>=k
pq.pop();
pq.push(v);
}
}
}
int add(int val) {
if (pq.size() < k) pq.push(val); //最小堆的大小<k時,直接新增新的元素,此時至少有k個元素
else if (val >= pq.top()) { //pq.size() >= k
pq.pop();
pq.push(val);
}
return pq.top();
}
};
執行效率如下:
執行用時:76 ms, 在所有 C++ 提交中擊敗了74.80% 的使用者
記憶體消耗:20 MB, 在所有 C++ 提交中擊敗了32.25% 的使用者
如果使用Python,可以 import heapq
, heapq
就是使用小頂堆實現的優先佇列:
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = nums
heapq.heapify(self.heap) # 小頂堆實現的優先佇列
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val: int) -> int:
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif val > self.heap[0]:
heapq.heapreplace(self.heap, val)
return self.heap[0]
相關文章
- LeetCode Kth Largest Element in an ArrayLeetCode
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- 215. Kth Largest Element in an Array
- 【LEETCODE】模擬面試-215. Kth Largest EleLeetCode面試
- [LeetCode] 230. Kth Smallest Element in a BSTLeetCode
- [LeetCode] 378. Kth Smallest Element in a Sorted MatrixLeetCode
- leetcode.5601. 設計有序流(design-an-ordered-stream)LeetCode
- Leetcode(easy heap)LeetCode
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- leetcode 368. Largest Divisible SubsetLeetCode
- LeetCode C++ 204. Count Primes【Math/Hash Table】簡單LeetCodeC++
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- [LeetCode] 1545. Find Kth Bit in Nth Binary StringLeetCode
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- [LeetCode] 705. Design HashSetLeetCode
- C++簡單vectorC++
- [leetcode]remove-elementLeetCodeREM
- 簡單記錄node中的Stream(流)
- 「LeetCode By Python」簡單篇(一)LeetCodePython
- 【LeetCode】簡單題目集LeetCode
- [LeetCode] 641. Design Circular DequeLeetCode
- [LeetCode] 362. Design Hit CounterLeetCode
- leetcode 127. 單詞接龍(C++)LeetCodeC++
- LeetCode 169. Majority ElementLeetCode
- leetcode-27. Remove ElementLeetCodeREM
- Leetcode 27 Remove-ElementLeetCodeREM
- Element Plus 和 Ant Design Vue哪個好Vue
- LeetCode 1 兩數之和(簡單)LeetCode
- LeetCode #1:Two Sum(簡單題)LeetCode
- [LeetCode] 635. Design Log Storage SystemLeetCode
- C++ - 簡單工廠模式C++模式
- 簡單認識和使用node 中的流(stream)
- leetcode 283. 移動零(簡單)LeetCode
- Largest Submatrix of All 1’s(思維+單調棧)