코딩테스트
뇌주름 살리기 - 19
라퐁
2025. 2. 4. 23:10
특이한 정렬
정수 n
을 기준으로 n
과 가까운 수부터 정렬하려고 합니다. 이때 n
으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치합니다. 정수가 담긴 배열 numlist
와 정수 n
이 주어질 때 numlist
의 원소를 n
으로부터 가까운 순서대로 정렬한 배열을 return하도록 solution 함수를 완성해주세요.
function solution(numlist, n) {
let answer = [];
//n이 numlist에 없으면 넣어주고, 있으면 answer에 넣어주기
if(numlist.indexOf(n) === -1) {
numlist.push(n);
} else {
answer.push(n);
}
numlist.sort((x, y) => x - y);
//left와 right의 끝은 각각 -1과 length로 구분
let length = numlist.length;
let left = numlist.indexOf(n) === 0 ? -1 : numlist.indexOf(n) - 1;
let right = numlist.indexOf(n) === length - 1 ? length : numlist.indexOf(n) + 1;
let absL = 0;
let absR = 0;
let isEndL = left < 0 ? true : false;
let isEndR = right === length ? true : false;
while(!isEndL || !isEndR) {
if(isEndL) { //left 끝이니까 right만 진행
answer.push(numlist[right]);
right += 1;
if(right === length) isEndR = true;
} else if(isEndR) { //right 끝이니까 left만 진행
answer.push(numlist[left]);
left -= 1;
if(left < 0) isEndL = true;
} else {
//left와 right의 절대값 크기 비교로 정렬 수행
absL = Math.abs(n - numlist[left]);
absR = Math.abs(n - numlist[right]);
if(absL === absR) {
answer.push(numlist[right]);
answer.push(numlist[left]);
right += 1;
left -= 1;
if(left < 0) isEndL = true;
if(right === length) isEndR = true;
} else if(absL < absR) {
answer.push(numlist[left]);
left -= 1;
if(left < 0) isEndL = true;
} else if(absL > absR) {
answer.push(numlist[right]);
right += 1;
if(right === length) isEndR = true;
}
}
}
return answer;
}