프로그래머스 - 귤 고르기

‍bng4535·2023년 2월 21일
0
post-thumbnail

문제

https://school.programmers.co.kr/learn/courses/30/lessons/138476

풀이

귤의 크기에 따라 해당 크기의 귤이 몇 개씩 존재하는지 확인하기 위해 맵 자료구조를 사용하였다. 이후 맵에 있는 값들을 하나씩 확인하면서 최대힙에 삽입하고, 하나씩 꺼내면서 더해진 총 합과 k를 비교하여 답을 구했다.

코드

import java.util.HashMap;
import java.util.PriorityQueue;

class Solution {

    public int solution(int k, int[] tangerine) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<tangerine.length; i++){
            map.put(tangerine[i], map.getOrDefault(tangerine[i], 0) + 1);
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>((o1,o2)->o2-o1);
        for( int a : map.keySet()){
            pq.add(map.get(a));
        }

        int count =0;
        int sum =0;
        while(sum<k) {
            sum+= pq.poll();
            count++;
        }
        return count;
    }
}
profile
공부 기록

0개의 댓글

관련 채용 정보