-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargestElement.java
More file actions
46 lines (39 loc) · 1.09 KB
/
Copy pathKthLargestElement.java
File metadata and controls
46 lines (39 loc) · 1.09 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
39
40
41
42
43
44
45
46
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.stream.IntStream;
class MyKthLargest {
private int[] nums;
private int k;
public MyKthLargest(int k, int[] nums) {
this.nums = nums;
this.k = k;
}
public int add(int val) {
IntStream stream = Arrays.stream(nums);
nums = IntStream.concat(stream, IntStream.of(val)).toArray();
return Arrays.stream(nums).boxed().sorted(Comparator.reverseOrder()).limit(k).min(Integer::compare).orElse(0);
}
}
class KthLargest {
private PriorityQueue<Integer> heap = new PriorityQueue<>();
private int k;
public KthLargest(int k, int[] nums) {
this.k = k;
for (int num : nums) {
add(num);
}
}
public int add(int val) {
heap.offer(val);
if (heap.size() > k) {
heap.poll();
}
return heap.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/