[Heap / Priority Queue, Medium] Kth Largest Element in an Array

송재호·2025년 4월 1일
0

https://leetcode.com/problems/kth-largest-element-in-an-array/description/?envType=study-plan-v2&envId=leetcode-75

소팅하지 않고 풀어야 한다.
Quickselect 알고리즘이나 우선순위 큐 사용해야 할 듯

PriorityQueue 사용해서 풀어본다.
아이디어는 오름차순 우선순위큐, nums 순회하면서 offer
단, queue size > k이면 poll()해서 가장 작은 값을 뺀다.

즉 최종적으로는 큐에 오름차순으로 가장 큰 k개의 숫자만 남게 되는데
이 때 peek()또는 poll()하면 남은 값 중 가장 작은 값 (== k번째 값) 얻을 수 있음

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int n : nums) {
            pq.offer(n);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        return pq.poll();
    }
}
profile
식지 않는 감자

0개의 댓글