[프로그래머스] 2019 KAKAO BLIND RECRUITMENT 실패율 자바코드

mango·2023년 9월 16일
0

프로그래머스 level 1

목록 보기
16/17

* Things I learnt

1. HashMap - value로 정렬한 key 순서

  • 오름차순
ArrayList<Integer> keySet = new ArrayList<Integer>(failRatio.keySet());    

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

->참고로 value 값이 같으면 key값이 작은것부터 정렬됨

  • 내림차순
ArrayList<Integer> keySet = new ArrayList<Integer>(failRatio.keySet());    

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

->참고로 value 값이 같으면 key값이 작은것부터 정렬됨

* 알고리즘

  1. 스테이지 수(N)만큼 반복
  2. 해당 레벨인 사람은 실패한것이므로 stages에서 해당 레벨인 갯수를 분자로 설정
  3. 해당 레벨보다 작으면 스테이지에 도달하지 못한 사람이므로 빼고 분모로 설정
  4. 스테이지에 맞는 실패율을 구함. value 값으로 빠르게 정렬해야하므로 HashMap에 put
  5. 값으로 정렬하고 싶으므로 먼저 HashMap의 keySet을 담은 ArrayList 만들기
  6. Collections.sort 함수를 사용해서 실패율 HashMap.get(o1) 로 값끼리 내림차순 정렬하고, 그에 맞게 keySet도 정렬함

*자바코드

import java.util.*;

class Solution {
    public int[] solution(int N, int[] stages) {
        int[] answer = new int[N];
        
        double motherNum = stages.length;
        double failNum = 0;
        HashMap<Integer, Double> failRatio = new HashMap<Integer, Double>();
        
        for(int i = 0; i < N; i++){
            failNum = 0;
            motherNum = stages.length;
            for(int now : stages){
                if(now < i+1) motherNum--;
                if(i+1 == now){
                    failNum++;
                }
            }
            if(motherNum != 0)
                failRatio.put(i+1, failNum/motherNum);
            else
                failRatio.put(i+1, 0.0);
        }

        ArrayList<Integer> keySet = new ArrayList<Integer>(failRatio.keySet());    
        Collections.sort( keySet,(o1, o2) -> (failRatio.get(o2).compareTo(failRatio.get(o1))) );
        
        int k = 0;
        for(int now : keySet){
            answer[k] = now;
            k++;
        }
        
        return answer;
    }
}


-> 깔끔하게 성공 ㅎ
해당 스테이지까지 못간 경우를 처음에 생각 못해서 분모가 0인 경우가 잘못 계산되었는데

if(motherNum != 0)
	failRatio.put(i+1, failNum/motherNum);
else

사용해서 해결했음

profile
앎의 즐거움을 아는 나는 mango ♪

0개의 댓글