-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode703.java
More file actions
37 lines (33 loc) · 1001 Bytes
/
LeetCode703.java
File metadata and controls
37 lines (33 loc) · 1001 Bytes
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
import java.util.PriorityQueue;
public class LeetCode703 {
public static void main(String[] args) {
KthLargest kthLargest = new KthLargest(3, new int[] { 4, 5, 8, 2 });
System.out.println(kthLargest.add(3)); // return 4
System.out.println(kthLargest.add(5)); // return 5
System.out.println(kthLargest.add(10)); // return 5
System.out.println(kthLargest.add(9)); // return 8
System.out.println(kthLargest.add(4)); // return 8
}
}
class KthLargest {
PriorityQueue<Integer> pq;
int k;
public KthLargest(int k, int[] nums) {
this.k = k;
this.pq = new PriorityQueue<>();
for (int num : nums) {
add(num);
}
}
public int add(int val) {
if (pq.size() < k) {
this.pq.offer(val);
} else {
if (this.pq.peek() < val) {
this.pq.poll();
this.pq.offer(val);
}
}
return this.pq.peek();
}
}