703. 数据流中的第 K 大元素

一、题目描述

设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
示例:
输入:
[“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

二、题解
方法一:小顶堆
维护长度为k的小顶堆,堆顶元素即为第k大的元素

class KthLargest {
    
    
    private PriorityQueue<Integer> heap = new PriorityQueue<>();
    private int k;

    public KthLargest(int k, int[] nums) {
    
    
        this.k = k;
        int n = Math.min(k,nums.length);
        int i=0;
        for(;i<n;i++){
    
    
            heap.offer(nums[i]);
        }
        while(i<nums.length){
    
    
            if(nums[i]>heap.peek()){
    
    
                heap.poll();
                heap.offer(nums[i]);
            }
            i++;
        }
    }
    
    public int add(int val) {
    
    
        
        if(heap.isEmpty()||heap.size()<k){
    
    
            heap.offer(val);
        }
        else if(val>heap.peek()){
    
    
            heap.poll();
            heap.offer(val);
        }
        return heap.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

在这里插入图片描述
优化:

class KthLargest {
    
    
    private PriorityQueue<Integer> heap = new PriorityQueue<>();
    private int k;

    public KthLargest(int k, int[] nums) {
    
    
        this.k = k;
        
        for(int num:nums){
    
    
            add(num);
        }
        
    }
    
    public int add(int val) {
    
    
        heap.offer(val);
        if(k<heap.size()){
    
    
            heap.poll();
        }
        return heap.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38748148/article/details/113789099
今日推荐