문제
내가 작성한 정답
class Solution {
public int solution(int[] array, int n) {
int answer = 0;
int min = 99;
for(int i:array){
if(Math.abs(n-i)==min){
answer = Math.min(i,answer);
}
else if(Math.abs(n-i)<min){
min = Math.abs(n-i);
answer = i;
}
}
return answer;
}
}다른 사람들의 정답
import java.util.*;
class Solution {
public int solution(int[] array, int n) {
int answer = 0;
Arrays.sort(array);
for(int i = 1 ; i < array.length ; i++){
if(Math.abs(n-array[0]) > Math.abs(n-array[i])){
array[0] = array[i];
}
}
answer = array[0];
return answer;
}
}
import java.util.Arrays;
import java.util.stream.Collectors;
class Solution {
public int solution(int[] array, int n) {
return Math.min(array[Arrays.stream(array)
.map(operand -> Math.abs(n - operand))
.boxed().collect(Collectors.toList())
.indexOf(Arrays.stream(array).
map(operand -> Math.abs(n - operand))
.min()
.orElse(0))], array[Arrays.stream(array)
.map(operand -> Math.abs(n - operand))
.boxed().collect(Collectors.toList())
.lastIndexOf(Arrays.stream(array)
.map(operand -> Math.abs(n - operand))
.min()
.orElse(0))]);
}
}Share article