C++的STL 堆 实现获取数组堆第K大的数
生活随笔
收集整理的這篇文章主要介紹了
C++的STL 堆 实现获取数组堆第K大的数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
堆數(shù)據(jù)結(jié)構(gòu) 使用的是優(yōu)先級(jí)隊(duì)列實(shí)現(xiàn),創(chuàng)建堆的時(shí)候需要指定堆中元素的排列方式,即最大堆或者最小堆
最大堆即 堆頂元素為堆中最大的元素
最小堆即 堆頂元素為堆中最小堆元素
如下為一個(gè)最大堆
回到文章標(biāo)題,獲取一個(gè)數(shù)組中第K大的數(shù),要求時(shí)間復(fù)雜度是O(n),即一次遍歷即可獲取到該值。
所以普通的先排序,再獲取第k個(gè)數(shù)值的方式顯然不滿足要求,排序最快的快速排序也需要O(log2 n)
這里就是我們前言中提到的堆 數(shù)據(jù)結(jié)構(gòu)堆優(yōu)勢(shì)了,可以構(gòu)建一個(gè)最小堆,堆頂始終為堆中所有元素的最小值。當(dāng)然在本次實(shí)現(xiàn)中,僅需要將堆堆大小限制為要求的K個(gè)即可,此時(shí)遍歷完數(shù)組的元素,堆頂即為數(shù)組中第K大的值。
基本過程如下圖:
實(shí)現(xiàn)如下(文末有測(cè)試代碼):
int calculte_k_maxnum(vector<int> &arr, int k) {priority_queue <int,vector<int>, greater<int>> small_heap;//有銜接隊(duì)列構(gòu)建最小堆if (arr.empty()) {print_erro("the array is empty\n",__LINE__);}/*按照步驟入堆*/for(int i =0;i < arr.size(); ++i) {if (small_heap.size() < k) {small_heap.push(arr[i]);} else if (small_heap.size() == k && small_heap.top() < arr[i]) {small_heap.pop();small_heap.push(arr[i]);}}/*最終的堆頂元素即為第K大的元素*/return small_heap.top();
}
測(cè)試代碼如下:
#include <iostream>
#include <queue>
#include <vector>using namespace std;void print_erro(string s,int line) {cout << s <<" " << line << endl;exit(-1);
}int calculte_k_maxnum(vector<int> &arr, int k) {priority_queue <int,vector<int>, greater<int>> small_heap;if (arr.empty()) {print_erro("the array is empty\n",__LINE__);}for(int i =0;i < arr.size(); ++i) {if (small_heap.size() < k) {small_heap.push(arr[i]);} else if (small_heap.size() == k && small_heap.top() < arr[i]) {small_heap.pop();small_heap.push(arr[i]);}}return small_heap.top();
}int main(){vector<int> arr;int k;int tmp;cout << "input the number of arr you want to get max " << endl;cin >> k;cout << "input the arr number " << endl;for (int i = 0;i < 5; ++i) {cin >> tmp;arr.push_back(tmp);}cout << "the k's max number of arr is " << calculte_k_maxnum(arr,k) << endl;return 0;
}
輸出如下:
input the number of arr you want to get max
4
input the arr number
2 4 3 6 7
the k's max number of arr is 3input the number of arr you want to get max
1
input the arr number
1 4 7 9 6
the k's max number of arr is 9
總結(jié)
以上是生活随笔為你收集整理的C++的STL 堆 实现获取数组堆第K大的数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++的STL 栈 实现四则运算
- 下一篇: C++的 STL堆 实现获取中位数