Leetcode 703. 数据流中的第K大元素 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 703. 数据流中的第K大元素 解题思路及C++实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
解題思路:
使用一個(gè)最小堆來存儲(chǔ)數(shù)據(jù),在C++中,對應(yīng)是#include<queue>頭文件中的priority_queue。
程序邏輯:KthLargest類初始化的時(shí)候,先根據(jù)nums容器中的數(shù),生成包含k個(gè)數(shù)的最小堆;然后在每一次add操作的時(shí)候,更新最小堆,并返回根節(jié)點(diǎn),即最上面的元素。
C++中STL里的priority_queue用法可參考網(wǎng)址: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;//構(gòu)造函數(shù)中,先建好最小堆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);*/?
?
?
總結(jié)
以上是生活随笔為你收集整理的Leetcode 703. 数据流中的第K大元素 解题思路及C++实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 173. 二叉搜索树迭
- 下一篇: Leetcode 215. 数组中的第K