본문 바로가기
Algorithm/Programmers

[Programmers] Lv.0 / 특이한 정렬 / Java

by unknownomad 2025. 2. 11.

문제

 

풀이

import java.util.*;

class Solution {
    public int[] solution(int[] numlist, int n) {
        Arrays.sort(numlist);
        
        for (int i = 0; i < numlist.length; i++) {
            for (int j = 0; j < numlist.length; j++) {
                if (Math.abs(n - numlist[i]) <= Math.abs(n - numlist[j])) {
                    int tmp = numlist[i];
                    numlist[i] = numlist[j];
                    numlist[j] = tmp;
                }
            }
        }
        return numlist;
    }
}
import java.util.*;

class Solution {
    public int[] solution(int[] numlist, int n) {
        return Arrays.stream(numlist)
            .mapToObj(a -> (Integer) a) // 1. int[] 배열을 Integer 객체 스트림으로 변환
            .sorted((a, b) -> { // 2. 커스텀 비교 함수로 정렬
                int i = Math.abs(n - a); // 3. a와 n 간의 차이의 절댓값
                int j = Math.abs(n - b); // 4. b와 n 간의 차이의 절댓값
                if (i == j) { // 5. 차이가 같으면 내림차순 정렬
                    return b - a;
                } else { // 6. 차이가 다르면 차이의 오름차순 정렬
                    return i - j;
                }
            })
            .mapToInt(a -> a) // 7. Integer 객체 스트림을 다시 int[]로 변환
            .toArray(); // 8. 결과를 int[] 배열로 반환
    }
}

댓글