问题描述:
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Returns the element representing the kth largest element in the stream.
问题分析:
constructor里面有 public KthLargest(int k, int[] nums) {}, 不代表你的类里面的member variable一定是它们两个。member variable 里面可以有 k, 但数组不一定有。这道题把priority queue设为member variable,在constructor里面用循环语句把array里面的值加入到priority queue,以达到初始化的目的。
为了节省空间,这道题目用了和leetcode219题相似的做法。
(219题要求找数组中一定区间k以内的相同元素。当初我用的hashmap实现的。为了节省空间,我们可以用hashset实现,并且始终把set的容量设置为k,因为太久远的数字对运行结果没有影响。)
同理,这道题可以只保留优先队列最大的k个元素,如果pq中元素个数大于k,我们删去queue头的(最小的)元素,不影响运行结果。
代码如下:
class KthLargest {
private int kthLargest;
private PriorityQueue<Integer> pq;
public KthLargest(int k, int[] nums) {
kthLargest = k;
pq = new PriorityQueue<Integer>();
for (int i=0; i<nums.length; i++){
pq.add(nums[i]);
if (pq.size()>k){
pq.poll();
}
}
}
public int add(int val) {
pq.add(val);
if (pq.size()>kthLargest){
pq.poll();
}
return pq.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
时间复杂度:O(nlogn)