Problem
- Give an array, find the integer that appears an odd number of times.
- 주어진 배열에서 홀수 회(number of times) 나타나는 정수를 찾는다.
- There will always be only one integer that appears an odd number of times.
Solution 01
function findOdd(arr) {
let count = {};
let result = 0;
for (let i = 0; i < arr.length; i++) {
if (!count[arr[i]]) {
count[arr[i]] = 1;
} else {
count[arr[i]]++;
}
}
for (let i in count) {
if (count[i] % 2 !== 0) {
result = i;
}
}
return parseInt(result);
}
findOdd([1, 2, 3, 2, 1]); // 3
findOdd([2, 2, 4, 2, 2]); // 4
Solution 02
function findOdd(arr) {
let count = 0;
let result = 0;
arr = arr.sort();
for (let i = 0; i < arr.length; i++) {
if (arr[i] === arr[i + 1]) {
count++;
} else {
count++;
if (count % 2 !== 0) {
result = arr[i];
break;
}
}
}
return result;
}
findOdd([1, 2, 3, 2, 1]); // 3
findOdd([2, 2, 4, 2, 2]); // 4
Solution 03
function findOdd(arr) {
let result = 0;
for (let i = 0; i < arr.length; i++) {
result = result ^ arr[i];
}
return result;
}
findOdd([1, 2, 3, 2, 1]); // 3
findOdd([2, 2, 4, 2, 2]); // 4
Solution 04
function findOdd(arr) {
return arr.reduce((a, b) => a ^ b, 0);
}
findOdd([1, 2, 3, 2, 1]); // 3
findOdd([2, 2, 4, 2, 2]); // 4