Problem
- You are given an array containing integers.
- The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer ‘N’.
- 배열은 단일 정수 ‘N’을 제외한 홀수 정수 또는 짝수 정수로 구성된다.
- Write a method that takes the array as an argument and returns this outlier ‘N’.
- 배열을 인수로 사용해서 이상값(outlier) ‘N’을 반환한다.
Solution 01
function findOutlier(arr) {
let even = [];
let odd = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even.push(arr[i]);
} else {
odd.push(arr[i]);
}
}
return even.length === 1 ? even[0] : odd[0];
}
findOutlier([0, 0, 1, 0, 0]); // 1 (The only odd number)
findOutlier([1, 1, 2, 1, 1]); // 2 (The only even number)
findOutlier([2, 4, 6, 7, 8]); // 7 (The only odd number)
Solution 02
function findOutlier(arr) {
let even = arr.filter(i => i % 2 === 0);
let odd = arr.filter(i => i % 2 !== 0);
return even.length === 1 ? even[0] : odd[0];
}
findOutlier([0, 0, 1, 0, 0]); // 1 (The only odd number)
findOutlier([1, 1, 2, 1, 1]); // 2 (The only even number)
findOutlier([2, 4, 6, 7, 8]); // 7 (The only odd number)