-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargest.java
More file actions
30 lines (26 loc) · 870 Bytes
/
Copy pathKthLargest.java
File metadata and controls
30 lines (26 loc) · 870 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
class KthLargest {
private PriorityQueue<Integer> minHeap;
private int k;
public KthLargest(int k, int[] nums) {
this.k = k;
this.minHeap = new PriorityQueue<>(k);
// Initialize the heap with the first k elements
for (int num : nums) {
add(num);
}
}
public int add(int val) {
if (minHeap.size() < k) {
minHeap.offer(val); // If less than k elements, add directly
} else if (val > minHeap.peek()) {
minHeap.poll(); // Remove the smallest element
minHeap.offer(val); // Add the new value
}
return minHeap.peek(); // The root of the heap is the k-th largest
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/