알고리즘 82 - Find the stray number

jabae·2021년 11월 1일
0

알고리즘

목록 보기
82/97

Q.

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples

[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

A)

function stray(numbers) {
  let numObj = numbers.reduce((obj, el) => {
    if (el in obj) obj[el] += 1;
    else obj[el] = 1;
    return obj;
  }, {});
  for (let el in numObj)
    if (numObj[el] === 1)
      return Number(el);
}

other

정규표현식으로 다를 경우를 반환하거나,

const stray = nums => nums.reduce((a, b) => a ^ b);

소트로 정렬하고 맨 앞에가 다를 경우, 앞의 수를 반환하거나 아닐 경우는 맨 뒤 큰 숫자가 다른 것이니 맨 뒤의 숫자를 반환하는 솔루션도 있다.

function stray(numbers) {
  var a = numbers.sort();
  
  if(a[0] != a[1]) {
    return a[0]
  } 
  return a[a.length-1]
}
profile
it's me!:)

0개의 댓글