알고리즘 - 가까운 수 - 120890

워니·2023년 4월 17일

알고리즘

목록 보기
17/29
post-thumbnail

[level 0] 가까운 수 - 120890

문제 링크

성능 요약

메모리: 72.7 MB, 시간: 2.11 ms

구분

코딩테스트 연습 > 코딩테스트 입문

채점결과


정확성: 100.0
합계: 100.0 / 100.0

문제 설명

정수 배열 array와 정수 n이 매개변수로 주어질 때, array에 들어있는 정수 중 n과 가장 가까운 수를 return 하도록 solution 함수를 완성해주세요.


제한사항
  • 1 ≤ array의 길이 ≤ 100
  • 1 ≤ array의 원소 ≤ 100
  • 1 ≤ n ≤ 100
  • 가장 가까운 수가 여러 개일 경우 더 작은 수를 return 합니다.

입출력 예
array n result
[3, 10, 28] 20 28
[10, 11, 12] 13 12

입출력 예 설명

입출력 예 #1

  • 3, 10, 28 중 20과 가장 가까운 수는 28입니다.

입출력 예 #2

  • 10, 11, 12 중 13과 가장 가까운 수는 12입니다.

※ 공지 - 2023년 3월 29일 테스트 케이스가 추가되었습니다. 기존에 제출한 코드가 통과하지 못할 수도 있습니다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges


  • 내 풀이
class Solution {
    public int solution(int[] array, int n) {
        int answer = 0;
        List<Integer> intList
                = Arrays.stream(array)
                .boxed()
                .collect(Collectors.toList());

        intList.add(n);
        Collections.sort(intList);

        if (n == Collections.max(intList)) {
            answer = intList.get(intList.size() - 2);
        } else if (n == Collections.min(intList)) {
            answer = intList.get(1);
        } else{
            int index = intList.indexOf(n);
            int compareLeft = intList.get(index) - intList.get(index - 1) ;
            int compareRight = intList.get(index + 1) - intList.get(index);
            if (compareRight < compareLeft){
                answer = intList.get(index + 1);
            }else{
                answer = intList.get(index - 1);
            }
        }
        return answer;
    }
}
  • 풀이
    int배열 형태를 Integer List로 변환 해주고
    매겨변수로 들어온 n을 list에 넣어줬다
    sort를 통해 정렬해줬고
    3가지의 경우로 나눴다
  1. n값이 list의 max값일경우 이미 sort를 진행했기떄문에 n값이 max일 경우에는
    n 의 index +1 값이 존재하지않는다 무조건 n의 index -1값이 answer
  2. n값이 list의 min값을 경우 위의 경우와 index값만 반대이다.
  3. 좌 우 index 값이 다 존재하는경우 n과 좌 우 index의 수의 차가 작은 수가 answer가 된다
    만약 차가 같다면 좌우 숫자중 더 작은수를 return한다
profile
Backend-Dev

0개의 댓글