본문 바로가기
개발로그/알고리즘

프로그래머스 Lv.0 특이한 정렬

by 쩜징 2023. 7. 30.

프로그래머스 Lv.0 특이한 정렬


문제 설명

정수 n을 기준으로 n과 가까운 수부터 정렬하고자 한다.

이때 n으로부터 거리가 같다면

더 큰 수를 앞에 오도록 배치한다.

정수가 담긴 배열 numlist와 정수 n이 주어질 때

numlist의 원소를 n으로부터

가까운 순서대로 정렬한 배열을 return하라.

 

1 ≤ n ≤ 10,000

1 ≤ numlist의 원소 ≤ 10,000

1 ≤ numlist의 길이 ≤ 100

numlist는 중복된 원소를 갖지 않는다.

numlist n result
[1, 2, 3, 4, 5, 6] 4 [4, 5, 3, 6, 2, 1]
[100000, 20, 36, 47, 40, 6, 10, 7000] 30 [36, 40, 20, 47, 10, 6, 7000, 10000]

** 풀이 방법

 

이것저것 시도했는데 풀지 못해서

다른 분의 풀이를 참고했다.

 

double형 배열을 생성해서

1) numlist의 원소 - n이 음수일 때

차이값의 절대값에 + 0.5를 더한다.

numlist의 원소가 작을수록

n과의 차이가 음수가 되기 때문에

차이값이 같은 원소보다

뒤쪽에 배치되기 위해 0.5를 더한다.

 

2) 양수일 때

두 수의 차이값을 배열에 저장한다.

double[] res = new double[numlist.length];
for (int i=0; i<numlist.length; i++) {
    if (numlist[i] - n < 0) 
        res[i] = Math.abs(numlist[i]-n) + 0.5;
    else
        res[i] = numlist[i] - n;
}

 

double형 배열을 오름차순으로 정렬한다.

Arrays.sort(res);

 

res배열의 원소가 1로 딱 나누어 떨어진다면

n + (int)res[i];을 저장하고

나누어 떨어지지 않는다면 0.5가 더해진 원소이기 때문에

n - (int)res[i];를 저장한다.

for (int i=0; i<numlist.length; i++) {
    if (res[i]%1!=0)
        answer[i] = n - (int)res[i];
    else
        answer[i] = n + (int)res[i];
}

<> 전체 코드 </>

import java.util.*;
class Solution {
    public int[] solution(int[] numlist, int n) {
        int[] answer = new int[numlist.length];
        double[] res = new double[numlist.length];
        for (int i=0; i<numlist.length; i++) {
            if (numlist[i] - n < 0) 
                res[i] = Math.abs(numlist[i]-n) + 0.5;
            else
                res[i] = numlist[i] - n;
        }
        Arrays.sort(res);
        for (int i=0; i<numlist.length; i++) {
            if (res[i]%1!=0)
                answer[i] = n - (int)res[i];
            else
                answer[i] = n + (int)res[i];
        }
        return answer;
    }
}

반응형

댓글