[프로그래머스] 특이한 정렬 - JAVA

2023. 4. 23. 19:17프로그래머스 - JAVA

문제 설명

정수 n을 기준으로 n과 가까운 수부터 정렬하려고 합니다. 이때 n으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치합니다. 정수가 담긴 배열 numlist와 정수 n이 주어질 때 numlist의 원소를 n으로부터 가까운 순서대로 정렬한 배열을 return하도록 solution 함수를 완성해주세요.

 

제한사항

1 ≤ n ≤ 10,000
1 ≤ numlist의 원소 ≤ 10,000
1 ≤ numlist의 길이 ≤ 100
numlist는 중복된 원소를 갖지 않습니다.

 

코드

import java.util.*;

class Solution {
    public int[] solution(int[] numlist, int n) {
        ArrayList<Integer> arr = new ArrayList<>();
        int[] clon = new int[numlist.length];

        numlist = Arrays.stream(numlist)
                .boxed()
                .sorted(Collections.reverseOrder())
                .mapToInt(m -> m)
                .toArray();

        for (int i = 0;i<numlist.length;i++)
            clon[i] = Math.abs(numlist[i]-n);

        Arrays.sort(clon);
        for(int i = 0;i<numlist.length;i++){
            for(int k = 0;k<numlist.length;k++){
                if(Math.abs(numlist[k]-n)==clon[i] && !arr.contains(numlist[k]))
                        arr.add(numlist[k]);
            }
        }
        return arr.stream().mapToInt(q -> q).toArray();
    }
    
}

 

 

 

 

 

 

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges