CodeWars 코딩 문제 2021/08/20 - Find the odd int

이호현·2021년 8월 20일
0

Algorithm

목록 보기
131/138

[문제]

Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

Examples
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] shold return 4, because it appears 1 time (which is odd).

(요약) 주어진 정수 배열에서 반복으로 나타나는 횟수가 홀수인 숫자를 찾아라.

[풀이]

function findOdd(A) {
  let answer = 0;
  const set = new Set(A);

  set.forEach(num => {
    const len = A.filter(n => n === num).length;
 
    if(len % 2) answer = num;
  })
 
  return answer;
}

Set을 이용해 중복되는 숫자를 제거한다.
Set에 있는 숫자들을 하나씩 주어진 배열에서 filter를 이용해 개수가 홀수인 숫자를 찾아서 return.

function findOdd(A) {
  A.sort((a, b) => a - b);

  for(let i = 0; i < A.length; i += 2) {
    if(A[i] !== A[i + 1]) return A[i];
  }
}

또 다른 풀이를 생각해봤다.
배열을 sort했을 때, 개수가 짝수인 숫자는 홀수 번째와 그 다음의 숫자가 같아야 한다.

예를 들어 [1, 1, 2, 2, 2] 일 때를 보면 1이 등장하는 위치는 첫번째, 두번째이다.
세번째, 네번째 숫자는 2로 같다.
다섯번째 숫자는 2지만 다음에 숫자가 없으므로 2가 답이다.

[1, 2, 2, 3, 3]을 보면 1이 홀수 번째지만 그 다음 숫자는 1이 아니다.
이 경우 바로 1이 답이 된다.

그래서 홀수 번째 숫자와 그 다음 숫자가 다르게 되는 처음 위치를 찾고, 거기에 위치한 숫자를 return하면 된다.

profile
평생 개발자로 살고싶습니다

0개의 댓글