Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 703. Kth Largest Element in a Stream #97

Open
Woodyiiiiiii opened this issue Apr 10, 2022 · 0 comments
Open

LeetCode 703. Kth Largest Element in a Stream #97

Woodyiiiiiii opened this issue Apr 10, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

  1. 用最小堆;
  2. 每次add元素进最小堆中,并不会比较堆顶,而是会重新排序
  3. 堆问题解决TOP K问题
  4. 此题是一道变种题,每次堆大小超过堆就抛出,起到比较和筛选的作用,取数也只跟堆顶有关,跟堆内元素无关
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);
 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant