703. The Kth largest element in the data stream
Design of the first data stream to find a k
class of large elements (class). Note that after the ordination of k
major elements, is not the first k
different elements.
Please realize KthLargest
categories:
KthLargest(int k, int[] nums)
Integer k
and integer flow nums
initialize the object.
int add(int val)
The val
insert data stream nums
, the return current flow from the first k
large element.
Example:
输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]
解释:
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
prompt:
- 1 <= k <= 104
- 0 <= nums.length <= 104
- -104 <= nums[i] <= 104
- -104 <= val <= 104
- The add method can be called up to 104 times
- The title data guarantees that when looking for the k-th largest element, there are at least k elements in the array
Method 1: Priority queue
Problem-solving ideas
Ideas are not important, I wish you a happy new year! !
Reference Code
class KthLargest {
private PriorityQueue<Integer> queue;
private int k;
public KthLargest(int k, int[] nums) {
this.queue = new PriorityQueue<>();
this.k = k;
for (int val : nums) {
add(val);
}
}
public int add(int val) {
queue.offer(val);
if (queue.size() > k) {
queue.poll();
}
return queue.peek();
}
}
Results of the