forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KthLargest.java
28 lines (23 loc) · 836 Bytes
/
KthLargest.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
/*https://leetcode.com/problems/kth-largest-element-in-an-array/*/
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
//add the first k elements to min heap
for (int i = 0; i < k; ++i)
minHeap.add(nums[i]);
//for rest of the elements
for (int i = k; i < nums.length; ++i)
{
//if the element is greate than the root of the minheap
if (nums[i] > (Integer)minHeap.peek())
{
//remove it and add the current element
minHeap.poll();
minHeap.add(nums[i]);
}
}
/*this ensures that the largest k elements stay in the heap*/
//return the root
return minHeap.poll();
}
}