[Programmers] Lv0 특이한 정렬 Java

2023. 2. 1. 13:28CS/자료구조 & 알고리즘

728x90

문제 출처

[프로그래머스 코딩 테스트 연습]

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

 

프로그래머스

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

programmers.co.kr

 

문제 풀이

  • 자바에는 배열을 비교할 때 Arrays.sort()를 이용하면 편하다
  • Arrays.sort에 주어지는 익명 객체 Comparator를 작성하면 Comparator 바탕으로 정렬이 된다.
  • compare 메소드에서 비교 방식을 설정할 수 있다.
  • Math.abs로 절댓값을 얻는 방식을 통하여 거리를 얻도록 했다.
  • 거리가 같다면 큰 수를 앞으로 가져가게 했다.
  • 거리가 다르다면 거리가 가까운 순으로 정렬을 하도록 하였다.

 

소스 코드

import java.util.Arrays;
import java.util.Comparator;

public class Solution {

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

        Integer[] arr = Arrays.stream(numlist).boxed().toArray(Integer[]::new);
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                int a = Math.abs(o1-n);
                int b = Math.abs(o2-n);
                if (a == b)
                    return o2 - o1;
                return a - b;
            }
        });

        return Arrays.stream(arr).mapToInt(i->i).toArray();
    }
}
728x90