Skip to content

Commit

Permalink
Merge pull request #80 from taniya25/patch-2
Browse files Browse the repository at this point in the history
Kth Largest Element in an Array
  • Loading branch information
TharinduDilshan authored Oct 24, 2021
2 parents 2278a34 + d030c10 commit 620b933
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Java/Algorithm/KthLargestElement
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Problem:
Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
*/
import java.util.PriorityQueue;
import java.util.Scanner;

public class kthLargestInteger {

public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] input = {3,2,1,5,6,4};
int k = scn.nextInt();
System.out.println(checkKthLargest(input, k));
}

private static int checkKthLargest(int[] input, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < input.length; i++) {
pq.offer(input[i]);
if (pq.size()>k) pq.poll();
}
return pq.poll();
}
}

0 comments on commit 620b933

Please sign in to comment.