-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode215.java
More file actions
38 lines (34 loc) · 1.08 KB
/
LeetCode215.java
File metadata and controls
38 lines (34 loc) · 1.08 KB
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
32
33
34
35
36
37
38
import java.util.Arrays;
import java.util.PriorityQueue;
public class LeetCode215 {
public static void main(String[] args) {
// 输入: [3,2,1,5,6,4], k = 2
// 输出: 5
System.out.println(new Solution215_2().findKthLargest(new int[] { 3, 2, 1, 5, 6, 4 }, 2));
// 输入: [3,2,3,1,2,4,5,5,6], k = 4
// 输出: 4
System.out.println(new Solution215_2().findKthLargest(new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6 }, 4));
}
}
class Solution215_1 {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}
class Solution215_2 {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
for (int i = 0; i < nums.length; i++) {
if (queue.size() < k) {
queue.offer(nums[i]);
} else {
if (queue.peek() < nums[i]) {
queue.poll();
queue.offer(nums[i]);
}
}
}
return queue.poll();
}
}