Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e55b429

Browse files
Merge pull request #1 from GauravVarshikar/GauravVarshikar-Kth-Largest
Create 215-Kth-Largest-Element-in-an-Array.java
2 parents 01a2b36 + 76a043e commit e55b429

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int findKthLargest(int[] nums, int k) {
3+
//create a min heap
4+
PriorityQueue<Integer> heap = new PriorityQueue();
5+
6+
//iterate over the array
7+
for(int n: nums){
8+
//first add the integer to heap
9+
heap.add(n);
10+
//if size of the heap is greater than k
11+
if(heap.size() > k){
12+
//remove the root element (lowest of all)
13+
heap.poll();
14+
}
15+
}
16+
//finally heap has k largest elements left with root as the kth largest element
17+
return heap.peek();
18+
}
19+
}

0 commit comments

Comments
 (0)