Featured image of post Single Number

Single Number

136. 只出现一次的数字

分析

异或运算具有以下性质:

  1. x ^ x = 0: 任何数字与自身异或结果为 0
  2. x ^ 0 = x: 任何数字与 0 异或结果为自身
  3. 满足交换律和结合律

通过对数组中的所有数字进行异或操作,成对出现的数字会互相抵消,最终只剩下那个只出现一次的数字

时间复杂度

总时间复杂度 O(n)

空间复杂度

空间复杂度为 O(1)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution
{
public:
    int singleNumber(vector<int>& nums)
    {
        int res = 0; // 初始化结果为 0
        for (int num : nums) // 遍历数组
            res ^= num; // 将每个数字与 res 进行异或操作
        return res; // 返回结果
    }
};
Built with Hugo
Theme Stack designed by Jimmy