您的位置:首页 > 其它

136. Single Number

2016-06-06 00:38 218 查看

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?

Analysis:

这道题可使用异或运算求解,主要用到以下性质:

1.异或运算符合交换律和结合律。即a^b=b^a; (a^b)^c=(a^b)^c

2.a^a=0

补充:异或运算的其他使用:使特定位翻转(^1),使特定位保持不变(^0)

Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
int singleNumber(vector<int>& nums) {
if (nums.empty()){
return -1;
}
int single_number = nums.at(0);
for (int i=1; i<nums.size(); i++){
single_number ^= nums.at(i);
}
return single_number;
}
};

int main() {
Solution sol;
vector<int> v;
cout << sol.singleNumber(v);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: