특이한 정렬

정수 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;
}

'코딩테스트' 카테고리의 다른 글

뇌주름 살리기 - 21  (0) 2025.02.08
뇌주름 살리기 - 20  (0) 2025.02.06
뇌주름 살리기 - 18  (0) 2025.02.02
뇌주름 살리기 - 17  (0) 2025.01.31
뇌주름 살리기 - 16  (0) 2025.01.25

+ Recent posts