Leetcode 703. 数据流中的第K大元素 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 703. 数据流中的第K大元素 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:
使用一個最小堆來存儲數據,在C++中,對應是#include<queue>頭文件中的priority_queue。
程序邏輯:KthLargest類初始化的時候,先根據nums容器中的數,生成包含k個數的最小堆;然后在每一次add操作的時候,更新最小堆,并返回根節點,即最上面的元素。
C++中STL里的priority_queue用法可參考網址:https://blog.csdn.net/xiaoquantouer/article/details/52015928
?
?
class KthLargest { public:priority_queue<int, vector<int>, greater<int>> pq;int n;KthLargest(int k, vector<int>& nums) {n = k;//構造函數中,先建好最小堆for(int i = 0; i < nums.size(); i++){pq.push(nums[i]);if(pq.size() > k) pq.pop();}}int add(int val) {//更新最小堆pq.push(val);if(pq.size() > n) pq.pop();return pq.top();} };/*** Your KthLargest object will be instantiated and called as such:* KthLargest* obj = new KthLargest(k, nums);* int param_1 = obj->add(val);*/?
?
?
總結
以上是生活随笔為你收集整理的Leetcode 703. 数据流中的第K大元素 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 173. 二叉搜索树迭
- 下一篇: Leetcode 215. 数组中的第K