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

Skip to content

Commit 76a043e

Browse files
Create 215-Kth-Largest-Element-in-an-Array.java
Solution of Kth Largest Element in an array using a heap Leetcode result: Runtime: 7 ms, faster than 45.05% of Java online submissions for Kth Largest Element in an Array. Memory Usage: 45.5 MB, less than 13.98% of Java online submissions for Kth Largest Element in an Array.
1 parent 01a2b36 commit 76a043e

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)