본문 바로가기

제로부터 C# 코딩테스트

프로그래머스 - 특이한 정렬

728x90

풀이

n과 가장 가까운 순으로 정렬 하는 문제 입니다.

 

단순 버블정렬을 이용해 풀거나

using System;

public class Solution {
    public int[] solution(int[] numlist, int n) {
      
        for(int i = numlist.Length-1; i>=0 ;i--)
        {
            for(int j = 0;j<i;j++)
            {
                if(Math.Abs(n-numlist[j]) > Math.Abs(n-numlist[j+1]))
                {
                    int term = numlist[j+1];
                    numlist[j+1] = numlist[j];
                    numlist[j] = term;
                }else if(Math.Abs(n-numlist[j]) == Math.Abs(n-numlist[j+1]))
                {
                    if(numlist[j]< numlist[j+1])
                    {
                         int term = numlist[j+1];
                         numlist[j+1] = numlist[j];
                         numlist[j] = term;
                    }
                }
            }
        }
        return numlist;
    }
}

 

"n과 가장 가까운 순" 이 정렬의 기준이기 때문에 그 조건으로 sort의 정렬 동작을 재정의해 푸는 방법과

  Array.Sort(numlist,(a,b)=>{
           if(Math.Abs(a-n) < Math.Abs(b-n)){
            return -1;
           }else if(Math.Abs(a-n) == Math.Abs(b-n)){
             if(a<b){
                return 1;
             }else{
                return -1;
             }
            }else{
               return 1;
           }
        });

 

Linq 라이브러리를 이용해 풀수 있습니다.

int[] answer = numlist.OrderBy(x => Math.Abs(x - n)).ThenByDescending(x => x).ToArray();

 

첫번째 정렬기준으로 Math.Abs(x -n )으로 오름차순 정렬,  두번째 정렬기준으로 ThenByDescending(x => x) 내림차순 정렬. ToArray()로 배열 반환.

728x90