题目描述:

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?

 

数组中的元素除了一个元素外,其他元素都有出现两次,题目要我们返回那唯一的一个元素。

解题思路:

这题我一开始是想用暴力破解的方法,用两层循环找唯一数,没有成功。后来上网看他人的解答时发现可以用位运算来做这一题:

异或运算的性质:1.a^a=0;2.a^0=a;3.a^b=b^a。

根据这三个性质,用0异或所有元素就可以找到唯一的元素了。

他人代码:

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int result=0;
 5         int length=nums.size();
 6         for(int i=0;i<length;i++)
 7             result^=nums[i];
 8         return result;
 9     }
10 };

 

posted on 2018-02-14 01:08  宵夜在哪  阅读(87)  评论(0编辑  收藏  举报