1. ๋ฌธ์ œ : https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

 

2. ํ’€์ด

pq์˜ ๊ธธ์ด ์ œํ•œ์œผ๋กœ ๊ฐ’์„ ์ปจํŠธ๋กคํ•˜๋Š” ๋ฐฉ์‹์„ ์ƒ๊ฐํ•ด์•ผํ•˜๋Š” ๋ฌธ์ œ

 

3. ์ฝ”๋“œ

import java.util.*;

public class KthLargest {

    private final PriorityQueue<Integer> q;
    private final int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        q = new PriorityQueue<Integer>();
        for (int a :nums) {
            add(a);
        }
    }

    public int add(int val) {
        q.offer(val);
        if (q.size() > k) {
            q.poll();
        }
        return q.peek();
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ