import java.util.*;
public class main {
    public static void main(String[] args) {

        Solution s = new Solution();

        System.out.println(Arrays.toString(s.Chap06Exmaple01(3, new int[] {15,27,12})));
        System.out.println(Arrays.toString(s.Chap06Example02(2, new String[]{"홍길동","이순신"}, new int[]{95,77})));
        System.out.println(s.Chap06Example03(5,3, new int[]{1,2,5,4,3}, new int[]{5,5,6,6,5}));
    }
}
class Solution {

    public int[] Chap06Exmaple01(int n, int[] arr) {

        List<Integer> list = new ArrayList<>();

        for(int a : arr)
            list.add(a);

        Collections.sort(list);
        Collections.reverse(list);

        for(int i = 0; i<arr.length;++i)
            arr[i] = (int)list.get(i);

        return arr;
    }
    public String[] Chap06Example02(int n, String[] name, int[] score) {
        String[] answer = new String[n];
        List<Score> list = new ArrayList<>();

        for(int i = 0; i<n;++i)
            list.add(new Score(name[i], score[i]));

        Collections.sort(list);

        for(int i = 0; i<n;++i)
            answer[i] = list.get(i).name;

        return answer;
    }
    public int Chap06Example03(int n, int k, int[] arrA, int[] arrB) {
        int answer = 0;

        Arrays.sort(arrA);
        Arrays.sort(arrB);
        for(int i = 0; i<k; ++i) {
            if(arrA[i] < arrB[arrB.length-i-1]) {
                arrA[i] = arrB[arrB.length-i-1];
            }
            else
                break;
        }
        for(int a : arrA)
            answer += a;
        return answer;
    }
}
class Score implements Comparable<Score> {
    public int score;
    public String name;
    public Score(String name, int score) {
        this.score = score;
        this.name = name;
    }
    @Override
    public int compareTo(Score s) {
        if(s.score < score)
            return 1;
        else if(s.score > score)
            return -1;
        else
            return 0;
    }
}

---

두 개 이상의 값을 동시에 정렬하라고 하면 클래스 만들고 Comaparable 상속 받고 하는게 내 기준에선 가장 편하다.

정렬 문제가 나올 때 라이브러리를 못쓰게 하지 않으면 라이브러리 그대로 쓰는게 제일 좋기도 하고

책도 답안을 보니 직접 구현하지 않더라...

+ Recent posts