道阻且长,行则将至,走慢一点没关系,不停下|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-15 17:24阅读: 7评论: 0推荐: 0

[LeetCode] LeeCode703. 数据流中的第K大元素

题目描述

思路:最小堆

好好领悟这个代码:

// 将nums数组所有元素插入小根堆中
for (int num : nums) {
	heap.offer(num);
	// 当小根堆的容量大于k时,就删除堆顶元素
	if (heap.size() > k) heap.poll();
}

当heap.size() == k的时候,还是会再添加一个元素,此时堆内部会已经排好序,并且heap.size()此时为k+1,此时需要执行poll()操作,保证heap的大小为K。

方法一:

class KthLargest {
    private PriorityQueue<Integer> heap;
    private int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.heap = new PriorityQueue<>();
        // 将nums数组所有元素插入小根堆中
        for (int num : nums) {
            heap.offer(num);
            // 当小根堆的容量大于k时,就删除堆顶元素
            if (heap.size() > k) heap.poll();
        }
    }
    
    public int add(int val) {
        heap.offer(val);
        if (heap.size() > k) 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);
 */

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17903830.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(7)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.