728x90
SMALL

using System;
using System.Linq;
using System.Diagnostics;

public class Solution {
    public int[] solution(int[] numlist, int n) {
        int[] answer = numlist.OrderBy(x => Math.Abs(x - n)).ThenByDescending(x => x).ToArray();
        
        return answer;
    }
}

 

////

 

using System;

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

 

 

자바

 

 

import java.util.*;
class Solution {
    public int[] solution(int[] numlist, int n) {
        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;
    }
}

 

 

import java.util.Arrays;

class Solution {
    public int[] solution(int[] numList, int n) {
        return Arrays.stream(numList)
                .boxed()
                .sorted((a, b) -> Math.abs(a - n) == Math.abs(b - n) ? b.compareTo(a) : Integer.compare(Math.abs(a - n), Math.abs(b - n)))
                .mapToInt(Integer::intValue)
                .toArray();
    }
}
728x90

설정

트랙백

댓글