카카오 - 실패율

greenTea·2023년 7월 19일
0
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        int N = 3;
        int[] ints = {1, 1, 1, 1};
        System.out.println(Arrays.toString(solution(N, ints)));
    }

    public static int[] solution(int N, int[] stages) {

        Queue<Node> queue = new PriorityQueue<>((a,b) ->  a.fail != b.fail ? Float.compare(b.fail ,a.fail) : a.index - b.index);

        int[] stageNumber = new int[N + 2];
        int people = stages.length;

        for (int stage : stages) {
            stageNumber[stage]++;
        }
        for (int i = 1; i < stageNumber.length-1; i++) {
            float fail = (float) stageNumber[i] / people;
            if (people ==0)
                fail = 0;
            queue.offer(new Node(fail,i));
            people -= stageNumber[i];
        }

        int[] answer = new int[N];
        for (int i = 0; i < answer.length; i++) {
            answer[i] = queue.poll().index;
        }

        return answer;

    }

    static class Node {
        private float fail;
        private int index;

        public Node(float fail, int index) {
            this.fail = fail;
            this.index = index;
        }
    }
}

🥳우선 순위 큐를 이용하여 풀었습니다.
1. 먼저 해당 스테이지 별로 실패율을 구하기 위해 해당 스테이지 별 인원 수를 계산합니다.

  1. 전체 사람수를 기준으로 1스테이지 부터 실패율을 구합니다.
    스테이지에 머물고 있는 사람 수 / 전체 사람 수
    이 때 전체 사람 수의 경우 스테이지 계산이 끝날 때마다 해당 스테이지의 머물고 있는 사람 수를 빼줘야 합니다.

  2. 해당 값을 우선 순위 큐에 넣기 -> 우선순위 큐에서는 실패율을 기준으로 정렬하되 같은 값의 경우 인덱스를 기준으로 오름차순으로 정렬하면 됩니다.

4.우선순위 큐에 있는 값을 하나 씩 꺼내어 정답값에 넣어주면 됩니다.🫡

출처 : 프로그래머스 스쿨

profile
greenTea입니다.

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

정말 좋은 글 감사합니다!

답글 달기