136. 只出现一次的数字

https://leetcode-cn.com/problems/single-number/

解法一:

这道题不像之前的540. Single Element in a Sorted Array是有序序列,更复杂. (看讨论的)用异或(XOR,或记为⊕) 以下结论很吊很有用:

0 ⊕ A = A //A为任意数
A ⊕ A = 0
即,任意数与0相与都等于其自身,任意数与其自身异或都为0

补充:
(A ⊕ B) ⊕ C = A ⊕ (B ⊕ C)  //结合律
(A ⊕ B) ⊕ (C ⊕ D) = A ⊕ B ⊕ C ⊕ D  //可以去掉括号
A ⊕ B ⊕ C ⊕ D = A ⊕ C ⊕ B ⊕ D  //可以随意交换

即,只要参与异或运算的成员不变,任意交换异或顺序,结果都一样
同理:
若f ⊕ m = G,则:
f ⊕ G = m //推导: f ⊕ G = f ⊕ (f ⊕ m) = f ⊕ f ⊕ m = 0 ⊕ m = m)
m ⊕ G = f //同上
//cpp
int singleNumber(vector<int>& nums) {
    for (int i = 1; i < nums.size(); i++) {  //遍历数组
        nums[0] ^= nums[i];  //直接用第0号存储异或结果,节省空间
    }
    return nums[0];
}
#py
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = nums[0]
        for i in range(1, len(nums)):
            res ^= nums[i]
        return res

最后更新于