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
하면 된다.