-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #80 from taniya25/patch-2
Kth Largest Element in an Array
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |