[프로그래머스 위클리 챌린지]#85002 6주차_복서 정렬하기

SeungBird·2021년 9월 17일
0

문제

복서 선수들의 몸무게 weights와, 복서 선수들의 전적을 나타내는 head2head가 매개변수로 주어집니다. 복서 선수들의 번호를 다음과 같은 순서로 정렬한 후 return 하도록 solution 함수를 완성해주세요.

  1. 전체 승률이 높은 복서의 번호가 앞쪽으로 갑니다. 아직 다른 복서랑 붙어본 적이 없는 복서의 승률은 0%로 취급합니다.
  2. 승률이 동일한 복서의 번호들 중에서는 자신보다 몸무게가 무거운 복서를 이긴 횟수가 많은 복서의 번호가 앞쪽으로 갑니다.
  3. 자신보다 무거운 복서를 이긴 횟수까지 동일한 복서의 번호들 중에서는 자기 몸무게가 무거운 복서의 번호가 앞쪽으로 갑니다.
  4. 자기 몸무게까지 동일한 복서의 번호들 중에서는 작은 번호가 앞쪽으로 갑니다.

입출력 예제

weightshead2headresult
[50,82,75,120]["NLWL","WNLL","LWNW","WWLN"][3,4,1,2]
[145,92,86]["NLW","WNL","LWN"][2,3,1]
[60,70,60]["NNN","NNN","NNN"][2,1,3]

풀이

이 문제는 우선순위큐를 이용해서 해당하는 조건의 복서를 순서대로 정렬해서 답을 출력할 수 있었다.

import java.util.PriorityQueue;

class Solution {
    public int[] solution(int[] weights, String[] head2head) {
        int[] answer = new int[weights.length];
        PriorityQueue<Boxer> pq = new PriorityQueue<>();
        
        for(int i=0; i<weights.length; i++) {
            String res = head2head[i];
            double percent = 0;
            int total = 0;
            int win = 0;
            int cnt = 0;
            int weight = weights[i];
            
            for(int j=0; j<res.length(); j++) {
                char c = res.charAt(j);
                if(c!='N') {
                    total++;
                    if(c=='W') {
                        win++;
                        if(weight<weights[j])
                            cnt++;
                    }
                }
            }
            if(total!=0)
                percent = (double)win/total;
     
            pq.add(new Boxer(i+1, percent, cnt, weight));
        }
        
        int idx = 0;
        while(!pq.isEmpty()) {
            answer[idx++] = pq.poll().idx;
        }
        
        
        return answer;
    }
    
    public class Boxer implements Comparable<Boxer>{
        int idx;
        double percent;
        int cnt;
        int weight;
        
        public Boxer(int idx, double percent, int cnt, int weight) {
            this.idx = idx;
            this.percent = percent;
            this.cnt = cnt;
            this.weight = weight;
        }
        
        public int compareTo(Boxer b) {
            if(this.percent==b.percent) {
                if(this.cnt == b.cnt) {
                    if(this.weight==b.weight)
                        return this.idx > b.idx ? 1 : -1;
                    
                    return this.weight < b.weight ? 1 : -1;
                }
                
                return this.cnt < b.cnt ? 1 : -1;
            }
            
            return this.percent < b.percent ? 1 : -1;
        }
    }
}
profile
👶🏻Jr. Programmer

0개의 댓글