Find the odd int
题目: 找出数组中出现奇数次数的数字
描述: 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] should return 4, because it appears 1 time (which is odd).
在线地址:Find the odd int
基础实现:统计每个数字出现的次数找出奇数次数的数字即可
function findOdd(A) {
var obj = {};
A.forEach(function(el){
obj[el] ? obj[el]++ : obj[el] = 1;
});
for(prop in obj) {
if(obj[prop] % 2 !== 0) return Number(prop);
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
看到这个问题,一般人想到的都是上面的解决方案,下面欣赏下网站上大佬给出的最佳实践:
利用异或运算符^的原理:相同数字异或结果为0,0与任意数异或为任意数;把所有数字依次异或即可剔出偶数次数的数字
const findOdd = (xs) => xs.reduce((a, b) => a ^ b);
1
上次更新: 2025/09/05, 8:09:00