-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthlargestelemt.java
More file actions
18 lines (16 loc) · 879 Bytes
/
Copy pathkthlargestelemt.java
File metadata and controls
18 lines (16 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k);
for(int i =0;i< k ; i++) pq.add(nums[i]);
for(int i =k;i< nums.length ; i++)
{
if(pq.peek()<nums[i])
{
pq.poll();
pq.add(nums[i]);
}
}
return pq.poll();
}
}
/* The idea is to construct a min-heap of size ->k and insert first k elements of array into the heap. Then for each of the remaining element of the array (A[k..n-1]) if that element is more than the root of the heap, we replace the root with current element. We repeat this process till array is exhausted. Now we will be left with largest elements of the array in the min-heap and k’th largest element will reside at the root of the min-heap.*/