LeetCode 136:Single Number I


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?
分析:
1つの整形配列は、ある要素を除いて、各要素に2回(Single Number IIに3回)現れ、1回しか現れない要素を見つけた.必要なのは、線形時間の複雑さ、余分な空間を使用しないことです.
Single Numberは比較的簡単で、残りの要素が2回現れたため、ビット演算ではN xor N=0で1回しか現れない要素を簡単に見つけることができます.コードは次のとおりです.
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int length = nums.size();
	int result = 0 ;
	for (int i=0; i<length; i++)
	{
		result ^= nums[i];
	}
	return result;
    }
};