
내가 작성한 코드
import java.util.*;
class Solution {
public int[] solution(int[] numlist, int n) {
return Arrays.stream(numlist)
.boxed() // int[]를 Integer[]로 변환
// 정렬
.sorted((a, b) -> {
int abs1 = Math.abs(a - n);
int abs2 = Math.abs(b - n);
// 차이가 같으면 값이 작은 순으로 정렬
// 차이가 다르면 차이가 작은 순으로 정렬
return abs1 == abs2 ? b - a : abs1 - abs2;
})
.mapToInt(Integer::intValue) // Integer[]를 int[]로 변환
.toArray();
}
}다른 사람의 코드
import java.util.*;
class Solution {
public int[] solution(int[] numlist, int n) {
0 1 2 3 4 5
int size = numlist.length;
for(int i=0; i<size-1; i++){
for(int k=i+1; k<size; k++){
int a = (numlist[i] - n) * (numlist[i] > n ? 1 : -1); // 절대값
int b = (numlist[k] - n) * (numlist[k] > n ? 1 : -1); // 절대값
if(a > b || (a == b && numlist[i] < numlist[k])){
// 두 값의 위치 교환
int temp = numlist[i];
numlist[i] = numlist[k];
numlist[k] = temp;
}
}
}
return numlist;
}
}Share article