forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_215.java
31 lines (24 loc) · 759 Bytes
/
_215.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.fishercoder.solutions;
import java.util.Collections;
import java.util.PriorityQueue;
/**
* 215. Kth Largest Element in an Array
*
* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
*/
public class _215 {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (int i : nums) {
maxHeap.offer(i);
}
while (k-- > 1) {
maxHeap.poll();
}
return maxHeap.poll();
}
}