[프로그래머스] 실패율

홈런볼·2023년 7월 18일

프로그래머스

목록 보기
16/36

문제링크

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

문제접근

사용할 자료구조 : 각 단계를 통과하지 못한 사람의 수를 보관하기 위해 map 선언
1. map을 선언한 후 N크기 이하의 키와 값을 생성
2. stages를 돌면서 각 stage의 유저 수를 구해 map에 저장
3. map을 돌면서 stages의 실패율을 구하고, map에 초기화
4. map을 실패율 기준으로 내림차순을 했을 때 키를 answer에 담아줌

코드

import java.util.*;

class Solution {
    public int[] solution(int N, int[] stages) {
        int[] answer = new int[N];

        Map<Integer,Double> map = new HashMap<>();

        for(int i=1;i<=N;i++){
            map.put(i,0.0);
        }

        for(int i=0;i<stages.length;i++){
            if(map.containsKey(stages[i])){
                map.put(stages[i],map.getOrDefault(stages[i],0.0)+1);
            }
        }

        List<Integer> keySet = new ArrayList<>(map.keySet());
        int users = stages.length;
        for (int key : keySet){
            if(map.get(key) == 0.0) continue;
            double value = map.getOrDefault(key,0.0) / users;
            users-= map.getOrDefault(key,0.0).intValue();
            map.put(key,value);
        }

        Collections.sort(keySet, (o1, o2) -> (map.get(o2).compareTo(map.get(o1))));

        int index = 0;
        for(int key : keySet){
            answer[index++] = key;
        }

        return answer;
    }
}

정확성 테스트

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

아주 유익한 내용이네요!

1개의 답글