프로그래머스 코딩테스트 입문 특이한 정렬 [JAVA] - 22년 10월 14일

Denia·2022년 10월 13일
0

코딩테스트 준비

목록 보기
97/201
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Solution {
    public Integer[] solution(int[] numlist, int n) {
        List<Integer> solution = IntStream.of(numlist).boxed().collect(Collectors.toList());

        solution.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                int o1Abs = Math.abs(o1 - n);
                int o2Abs = Math.abs(o2 - n);

                if (o1Abs == o2Abs) {
                    if (o1 > o2) return -1;
                    else if (o1 < o2) return 1;
                } else {
                    return o1Abs - o2Abs;
                }

                return 0;
            }
        });

        return solution.toArray(new Integer[0]);
    }
}

import java.util.stream.IntStream;

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

        return IntStream.of(numlist).boxed().sorted((o1, o2) -> {
            int o1Abs = Math.abs(o1 - n);
            int o2Abs = Math.abs(o2 - n);

            if (o1Abs == o2Abs) {
                if (o1 > o2) return -1;
                else if (o1 < o2) return 1;
            } else {
                return o1Abs - o2Abs;
            }

            return 0;
        }).toArray(Integer[]::new);
    }
}

profile
HW -> FW -> Web

0개의 댓글