[LeetCode]Single Number

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(n),空间复杂度O(1),说明只能遍历一遍。

说明其中存在什么规律在,可以一次遍历就能得到结果。

没错,就是位运算,这里用到的是异或。

a^a=0

0^a=a

所以出现两次的异或后都为0了,所有全部做异或运算,最后的结果就是出现一次的值。

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         if(nums.size()==0) return 0;
 5         int result=nums[0];
 6         for(int i=1;i<nums.size();i++)
 7         {
 8             result=result ^ nums[i];
 9         }
10         return result;
11     }
12 };
原文地址:https://www.cnblogs.com/Sean-le/p/4740775.html