javascript - 使用javascript查找数组中的任何重复元素

标签 javascript data-structures

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/

相关文章:

c++ - O(N) 中的锦标赛获胜者和 O(NLogN) 中的玩家排名

JavaScript 按值过滤

javascript - 在 MSCRM 2015 中使用 javascript 限制多实体查找

javascript - 在 Reactjs 中的自定义 DOM 节点中渲染内部组件

javascript - css 过渡不顺利发射

c++ - 使用对的矩阵乘法

file - FBX - 在 FBX 文件中,我应该使用哪些数据来构建模型的骨架并为其设置动画?

javascript - html5 音频歌曲只播放数组中的前 2 个?

javascript - Mongoose - 检测重复字段

javascript - 从 Javascript 数组创建嵌套对象