LeetCode 풀기 - 215. Kth Largest Element in an Array

백지우·2026년 9월 2일

LeetCode

목록 보기
25/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

215. Kth Largest Element in an Array

풀이

  • 방법:pq에 k개의 요소만 넣어 관리하기
class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();


        for(int num: nums){
            if(pq.size() < k) pq.offer(num);
            else{
                if(pq.peek() < num){
                    pq.poll();
                    pq.offer(num);
                }
            }
        }

        return pq.peek();
        
    }
}

  • 코드 작성하다가 느낀점
    - 방금 푼 703번도 pq하나로 풀 수 있을 듯.

0개의 댓글