본문 바로가기

Programmers/Level1

복서 정렬하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.*;
 
class Solution {
    public int[] solution(int[] weights, String[] head2head) {
        int n = weights.length;
        int[] answer = new int[n];
        ArrayList<Person> list = new ArrayList<Person>();
        
        // 선수 정보 계산
        for(int i=0;i<n;i++){
            int fight_count = 0;
            int heavy_count = 0;
            int winning_count = 0;
            float winning_rate = 0;
            for(int j=0;j<n;j++){
                if(head2head[i].charAt(j) == 'W'){
                    fight_count++;
                    winning_count++;
                    if(weights[j] > weights[i])
                        heavy_count++;
                } else if(head2head[i].charAt(j) == 'L')
                    fight_count++;
            }
            if(fight_count != 0)
                winning_rate = winning_count * 100 / (float) fight_count;
            list.add(new Person(i + 1, weights[i], fight_count, heavy_count, winning_count, winning_rate));
        }
 
        // 정렬
        Collections.sort(list, new Comparator<Person>(){
            @Override
            public int compare(Person o1, Person o2){
                float f_a = o2.winning_rate - o1.winning_rate;
                int a;
                if(f_a == 0){
                    a = o2.heavy_count - o1.heavy_count;
                    if(a == 0){
                        a = o2.weight - o1.weight;
                        if(a == 0)
                            a = o1.index - o2.index;
                    }
                } else 
                    return f_a > 0 ? 1 : -1;
                return a;
            }
        });
 
        for(int i=0;i<n;i++){
            answer[i] = list.get(i).index;
        }
        return answer;
    }
}
 
class Person {
    int index;
    int weight;
    int fight_count;
    int heavy_count;
    int winning_count;
    float winning_rate;
    public Person(int index, int weight, int fight_count, int heavy_count, int winning_count, float winning_rate){
        this.index = index;
        this.weight = weight;
        this.fight_count = fight_count;
        this.heavy_count = heavy_count;
        this.winning_count = winning_count;
        this.winning_rate = winning_rate;
    }
}
cs

Comparator를 이용하여 4가지 조건을 검사하였다.

'Programmers > Level1' 카테고리의 다른 글

나머지가 1이 되는 수 찾기  (0) 2021.10.25
최소직사각형  (0) 2021.10.11
없는 숫자 더하기  (0) 2021.10.10
상호 평가  (0) 2021.10.08
부족한 금액 계산하기  (0) 2021.10.08