如何理解利用按位异或来得到数组中不重复的项?



 var singleNumber = function(nums) {
    for(var i = 1,len = nums.length;i<len;i++) {
        nums[0] ^= nums[i]
    }
    return nums[0]
};

获取数组中只出现过一次的数字的算法,用到了XOR,但不太能理解


 singleNumber([1,3,1,4,6,4,6,5,3])

[3, 3, 1, 4, 6, 4, 6, 5, 3]
[7, 3, 1, 4, 6, 4, 6, 5, 3]
[1, 3, 1, 4, 6, 4, 6, 5, 3]
[5, 3, 1, 4, 6, 4, 6, 5, 3]
[3, 3, 1, 4, 6, 4, 6, 5, 3]
[6, 3, 1, 4, 6, 4, 6, 5, 3]
[5, 3, 1, 4, 6, 4, 6, 5, 3]

只记得自身的XOR会得到0

java python 算法 JavaScript c

湛泸剑EX 10 years, 4 months ago

没意义,你只有假设整个数组,只有唯一一个奇数出现的数字。有这样的场景吗?

很丑的企鹅 answered 10 years, 4 months ago

  1. a^a=0
  2. 0^a=a
  3. 异或满足交换率和结合率

因此a^b^c^b^c=a^(b^b)^(c^c)=a

狂暴的蛋蛋 answered 10 years, 4 months ago

Your Answer