diff --git a/java/215-Kth-Largest-Element-in-an-Array.java b/java/215-Kth-Largest-Element-in-an-Array.java new file mode 100644 index 000000000..f75ae35bb --- /dev/null +++ b/java/215-Kth-Largest-Element-in-an-Array.java @@ -0,0 +1,19 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + //create a min heap + PriorityQueue heap = new PriorityQueue(); + + //iterate over the array + for(int n: nums){ + //first add the integer to heap + heap.add(n); + //if size of the heap is greater than k + if(heap.size() > k){ + //remove the root element (lowest of all) + heap.poll(); + } + } + //finally heap has k largest elements left with root as the kth largest element + return heap.peek(); + } +}