-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
- 用最小堆;
- 每次add元素进最小堆中,并不会比较堆顶,而是会重新排序
- 堆问题解决TOP K问题
- 此题是一道变种题,每次堆大小超过堆就抛出,起到比较和筛选的作用,取数也只跟堆顶有关,跟堆内元素无关
class KthLargest {
PriorityQueue<Integer> queue;
int k = 0;
public KthLargest(int k, int[] nums) {
this.k = k;
queue = new PriorityQueue<>(k);
for (int num : nums) {
queue.add(num);
if (queue.size() > k) {
queue.poll();
}
}
}
public int add(int val) {
queue.add(val);
if (queue.size() > k) {
queue.poll();
}
return queue.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
Metadata
Metadata
Assignees
Labels
No labels