Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
我找到了一个解决方案
位操作 概念
If we take XOR of zero and some bit, it will return that bit
a \oplus 0 = aa⊕0=a
If we take XOR of two same bits, it will return 0
a \oplus a = 0a⊕a=0
a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ba⊕b⊕a=(a⊕a)⊕b=0⊕b=b
So we can XOR all bits together to find the unique number.
我尝试在 JavaScript 中实现相同的方法,如下所示
var singleNumber = function(nums) {
let a = 0
nums.forEach((i)=>{
console.log( a^=i)
console.log( a)
a^=i;
})
return a
};
console.log(singleNumber([2,2,1]))
但它没有给出正确的解决方案
最佳答案
您在每次迭代中都会执行a^=i
两次:
nums.forEach((i)=>{
console.log( a^=i)
console.log( a)
a^=i;
})
因此,a
的位被切换一次,然后又切换回来,因此结果始终为 0。
删除第一个console.log(a^=i)
,它就会工作:
var singleNumber = function(nums) {
let a = 0
nums.forEach((i)=>{
a^=i;
})
return a
};
console.log(singleNumber([2,2,1]))
更简洁地,使用reduce
:
const singleNumber = nums => nums.reduce((a, num) => a ^ num, 0);
console.log(singleNumber([2,2,1]))
如果您想记录^
的结果,请使用a ^ i
:
var singleNumber = function(nums) {
let a = 0
nums.forEach((i)=>{
console.log('a will become:', a ^ i);
a^=i;
})
return a
};
console.log(singleNumber([2,2,1]))
关于javascript - 使用javascript查找数组中的任何重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841874/