We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 0c7c84f + 43e51e3 commit 393923eCopy full SHA for 393923e
java/215-Kth-Largest-Element-in-an-Array.java
@@ -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