-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathKLargestElements.java
34 lines (29 loc) · 990 Bytes
/
KLargestElements.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*https://practice.geeksforgeeks.org/problems/k-largest-elements4206/1/*/
class Solution {
int[] kLargest(int[] arr, int n, int k) {
// code here
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
//add the first k elements to min heap
for (int i = 0; i < k; ++i)
minHeap.add(arr[i]);
//for rest of the elements
for (int i = k; i < arr.length; ++i)
{
//if the element is greate than the root of the minheap
if (arr[i] > (Integer)minHeap.peek())
{
//remove it and add the current element
minHeap.poll();
minHeap.add(arr[i]);
}
}
/*this ensures that the largest k elements stay in the heap*/
//return the root
int[] result = new int[k];
for (int i = k-1; i >= 0; --i)
{
result[i] = (Integer)minHeap.poll();
}
return result;
}
}