프로그래머스 귤 고르기 [JAVA] - 22년 12월 5일

Denia·2022년 12월 5일
0

코딩테스트 준비

목록 보기
112/201
post-custom-banner

객체 만들어서 사용

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    public int solution(int limit, int[] tangerine) {
        int answer = 0;

        int count = 0;

        Map<Integer, Tangerine> counter = new HashMap<>();

        for (int tangerineNumber : tangerine) {
            Tangerine curTangerine = counter.getOrDefault(tangerineNumber, new Tangerine(tangerineNumber, 0));
            curTangerine.count++;
            counter.put(tangerineNumber, curTangerine);
        }

        List<Tangerine> tangerines = new ArrayList<>(counter.values());

        tangerines.sort(null);

        for (Tangerine curTangerine : tangerines) {
            int tempCount = curTangerine.count;

            count += tempCount;
            answer++;

            if (count >= limit) {
                break;
            }
        }

        return answer;
    }
}

class Tangerine implements Comparable<Tangerine> {
    int number;
    int count;

    public Tangerine(int number, int count) {
        this.number = number;
        this.count = count;
    }

    @Override
    public int compareTo(Tangerine o) {
        return -Integer.compare(this.count, o.count);
    }
}

객체 없이 코드 작성

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    public int solution(int limit, int[] tangerine) {
        int answer = 0;

        int count = 0;

        Map<Integer, Integer> counter = new HashMap<>();

        for (int tangerineNumber : tangerine) {
            int curTangerine = counter.getOrDefault(tangerineNumber, 0);
            curTangerine++;
            counter.put(tangerineNumber, curTangerine);
        }
        List<Integer> tangerines = new ArrayList<>(counter.keySet());

        tangerines.sort((a, b) -> counter.get(b) - counter.get(a));

        for (Integer keyIdx : tangerines) {
            count += counter.get(keyIdx);
            answer++;

            if (count >= limit) {
                break;
            }
        }

        return answer;
    }
}

profile
HW -> FW -> Web
post-custom-banner

0개의 댓글