본문 바로가기

Java/프로그래머스

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

https://school.programmers.co.kr/learn/courses/30/lessons/120880

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

 

 

 

정답 

 

import java.util.*;

class Solution {
    public int[] solution(int[] numlist, int n) {
        int[] answer = new int[numlist.length];
        
        ArrayList<Integer> list = new ArrayList<>();
        
        for(int i=0; i<numlist.length; i++)
        {
            list.add(numlist[i]);
        }
        
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer n1, Integer n2)
            {
                int gap1 = Math.abs(n1 -n);
                int gap2 = Math.abs(n2-n);
                
                //차이가 같다면
                if(gap1==gap2)
                {
                    return n2 - n1; //값이 큰 것을 기준으로 정렬
                }
                
                return gap1 - gap2;
            }
        });
        
        for(int i=0; i<answer.length; i++)
        {
            answer[i] = list.get(i);
        }

            
        return answer;
    }
}

 

 

 

다른 사람의 풀이 

 

import java.util.PriorityQueue;

class Solution {
    public int[] solution(int[] numlist, int n) {

        PriorityQueue<Integer> que = new PriorityQueue<>(
                (a, b) -> Math.abs(a - n) == Math.abs(b - n) ? b - a : Math.abs(a - n) - Math.abs(b - n));

        for (int num : numlist)
            que.add(num);

        int idx = 0;

        while (!que.isEmpty())
            numlist[idx++] = que.poll();

        return numlist;
    }
}