메모리: 72.7 MB, 시간: 2.11 ms
코딩테스트 연습 > 코딩테스트 입문
정확성: 100.0
합계: 100.0 / 100.0
정수 배열 array와 정수 n이 매개변수로 주어질 때, array에 들어있는 정수 중 n과 가장 가까운 수를 return 하도록 solution 함수를 완성해주세요.
array의 길이 ≤ 100array의 원소 ≤ 100n ≤ 100| array | n | result |
|---|---|---|
| [3, 10, 28] | 20 | 28 |
| [10, 11, 12] | 13 | 12 |
입출력 예 #1
입출력 예 #2
※ 공지 - 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;
}
}