136. Single Number

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;
}

你可能感兴趣的:(136. Single Number)