数据流中的第 K 大元素
难度:
标签:
题目描述
代码结果
运行时间: 58 ms, 内存: 20.0 MB
/*
* Problem: Design a class to find the kth largest element in a stream of integers using Java Streams.
*
* Solution:
* - The logic remains similar to the non-stream implementation, using a min-heap.
* - The difference is in initialization, where we utilize Java Streams to populate the heap.
* - The add method is implemented similarly, checking the size of the heap and the value to be added.
*/
import java.util.PriorityQueue;
import java.util.stream.IntStream;
public class KthLargest {
private PriorityQueue<Integer> minHeap;
private int k;
public KthLargest(int k, int[] nums) {
this.k = k;
this.minHeap = new PriorityQueue<>(k);
// Use Streams to add initial elements
IntStream.of(nums).forEach(this::add);
}
public int add(int val) {
if (minHeap.size() < k) {
minHeap.offer(val);
} else if (val > minHeap.peek()) {
minHeap.poll();
minHeap.offer(val);
}
return minHeap.peek();
}
}
解释
方法:
这个题解的思路是使用一个最小堆来维护数据流中的前 k 个最大的元素。初始时,将 nums 中的元素加入堆中,如果堆的大小超过 k,则弹出堆顶元素(最小的元素),以保证堆中始终保留 k 个最大的元素。当新的元素 val 被添加到数据流中时,如果堆的大小小于 k,则直接将 val 加入堆中;如果 val 大于等于堆顶元素,则将堆顶元素替换为 val,然后调整堆。这样,堆顶元素始终是第 k 大的元素。
时间复杂度:
O(log k)
空间复杂度:
O(k)
代码细节讲解
🦆
在使用最小堆维护数据流中的前k个最大元素时,如何保证初始数组nums中的元素少于k个时的正确性?
▷🦆
如果数组nums中包含重复元素,这种最小堆的实现是否还能正确返回第k大的元素?
▷🦆
为什么选择使用最小堆而不是最大堆来解决这个问题,最小堆在这个场景下有什么优势?
▷🦆
在替换堆顶元素时,你使用了heapreplace方法。这个方法具体是如何工作的,与heappop后再heappush有什么区别?
▷