본문 바로가기
코테연습

26.Find The Parity Outlier

by hxunz 2022. 4. 2.

Description:

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.

Examples

[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)

 

 

function findOutlier(integers){
  const odd = [];
  const even = [];
  
  for (i = 0; i < integers.length; i++) {
    if (integers[i] % 2 === 0) {
      even.push(integers[i])
    } else {
      odd.push(integers[i])
    }
  }
  
  return (odd.length === 1) ? odd[0] : even[0];
}

배열 내에 요소가 짝수이면 새로 생성한 even 빈 배열에 넣어주고 

홀수이면 새로 생성한 odd 빈 배열에 넣어준다음에 

이 둘의 배열을 비교해서 길이가 1인 배열을 리턴해주었다. 

 

 

function findOutlier(int){
  var even = int.filter(a=>a%2==0);
  var odd = int.filter(a=>a%2!==0);
  return even.length==1? even[0] : odd[0];
}

이렇게 filter로 걸러냈으면 더 간단하게 할 수 있었을것같다ㅜ

'코테연습' 카테고리의 다른 글

28.Duplicate Encoder  (0) 2022.04.04
27.Counting Duplicates  (0) 2022.04.03
25.Create Phone Number  (0) 2022.04.02
24.Bit Counting  (0) 2022.04.01
23.Who likes it?  (0) 2022.04.01

댓글