How to find the K largest element in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <queue>

int findKLargest(std::vector<int> const &v, int K) {
    if (v.size() < K) {
        return -1;
    }
 
    std::priority_queue<int, std::vector<int>, std::greater<int>> pq(v.begin(), v.begin() + K);
    
    for (int i = K; i < v.size(); i++) {
        if (v[i] > pq.top()) {
            pq.pop();
            pq.push(v[i]);
        }
    }
 
    return pq.top();
}
 
int main()
{
    std::vector<int> v = { 100, 88, 98, 80, 50, 12, 35, 70, 60, 97, 85, 89  };
    int K = 4;
 
    std::cout << findKLargest(v, K);
}





/*
run:
 
89
 
*/

 



answered May 12, 2022 by avibootz
edited May 12, 2022 by avibootz
...