[Geeks for Geeks] k largest elements

k largest elements

Given an array Arr of N positive integers, find K largest elements from the array. The output elements should be printed in decreasing order.

  • Time : O(nlogk)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution{
public:
vector<int> kLargest(int arr[], int n, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int i = 0; i < n; i++) {
pq.push(arr[i]);
while(pq.size() > k) pq.pop();
}
vector<int> res(pq.size());
while(!pq.empty()) {
res[pq.size() - 1] = pq.top();
pq.pop();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/k-largest-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.