您的位置:首页 > 其它

LeetCode_136. Single Number

2017-01-30 10:26 330 查看
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?

题意理解:

给定一个整数数组,每个元素出现两次,除了一个,找出这个元素。(线性运行时间复杂度,无额外内存)

首先想到的是遍历,两次for循环,太暴力,时间复杂度O(n2)。

参考http://www.cnblogs.com/fanyabo/p/4180800.html后,

解题思路关键:异或。(a^b=b^a, 0^a=a)

那么假设给定一个数组[2,3,4,4,3,2,1,5,1],

2^3^4^4^3^2^1^5^1=5

C++:

class Solution{
public:
int singleNumber(vector<int>& nums)
{
int ele=0;
for (int i = 0; i<nums.size(); i++)
{
ele ^= nums[i];
}
return ele;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法