본문 바로가기
코딩테스트/프로그래머스

Level2 - 귤 고르기

by 고구마는호박고구마 2023. 5. 25.

귤들의 크기가 담긴 배열이 주어진다.

[1, 3, 2, 5, 4, 5, 2, 3]

1번 크기 1개2번 크기 2개3번 크기 2개4번 크기 1개5번 크기 2개

 

개수가 주어지는데 이 중 서로 다른 종류의 수의 최솟값을 리턴해라 6개의 개수가 주어진다면 2번 3번 4번을 담아야 최소크기로 6개를 담을 수 있다.키 값 형태로 접근

 

HashMap

class Solution {
    public int solution(int k, int[] tangerine) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        int max = 0;
        for(int x : tangerine){
            if(hashMap.containsKey(x)) hashMap.put(x,hashMap.get(x)+1);
            else hashMap.put(x, 1);
        }
        ArrayList<Integer> arr = new ArrayList<>();
        for(int x : hashMap.keySet()){
            arr.add(hashMap.get(x));
        }
        Collections.sort(arr, Collections.reverseOrder());
        int cnt = 0;
        for(int x : arr){
            k -= x;
            cnt++;
            if(k<=0) break;
        }

        return cnt;
    }
}

+ new ArrayList(map.values());

- 해시맵의 값들을 리스트 형식으로 출력

+ Collections.sort(arr, Collections.reverseOrder());

- 내림차순 정렬 

 

 

댓글