본문 바로가기
🫧 코테 : CodingTest

[프로그래머스] Java : 특이한 정렬

by 예옹이 2024. 4. 17.

 

문제

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

 

 

 

입출력 예

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

 

 

 


 

 

 

1. numlist정렬

Arrays.sort(numlist);

 

 

2. 이중 for문으로 n과 가까운 수 앞으로 뽑아주기

for(int i=0; i<numlist.length; i++){
	for(int j=0; j<numlist.length; j++){
		if(Math.abs(numlist[i]-n) <= Math.abs(numlist[j]-n)){
			int temp = numlist[i];
			numlist[i] = numlist[j];
			numlist[j] = temp;
		}
	}
}

 

n과 가까운 수임을 파악하기 위해서 numlist[i] - n에 절댓값을 씌워 확인했습니다.

 

 


 

 

 

코드

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(numlist[i]-n) <= Math.abs(numlist[j]-n)){
                    int temp = numlist[i];
                    numlist[i] = numlist[j];
                    numlist[j] = temp;
                }
            }
        }
        return numlist;
    }
}

 

 

 

 

 

제가 작성한 코드는 아래에서 확인하실 수 있습니다.

https://github.com/eonwy/programmers

 

GitHub - eonwy/programmers: 🔎 coding-test (programmers) 🔍

🔎 coding-test (programmers) 🔍. Contribute to eonwy/programmers development by creating an account on GitHub.

github.com