首页 > 代码库 > Leetcode-136 Single Number

Leetcode-136 Single Number

#136.  Single Number    

Given an 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?

题解:既然要求线性时间复杂度求解这题,空间复杂度为O(1).就不能暴力轮询啦。

然后就想起数电里面,XOR异或,相同的数异或是零。老实说,为啥我看到single想到了单身狗,两个配对的数一异或就归零哈哈。

然后就剩下了单身狗数。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int single=0;
        for(int i=0;i<nums.size();i++)
        {
            single=single^nums[i];
        }
        return single;
    }
};

 

      

Leetcode-136 Single Number