Single Number leetcode

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?

 

Subscribe to see which companies asked this question

 
这个题我首先想到的是用hashmap,第一次添加,第二次删除,剩下的没有删除的就是答案
int singleNumber(vector<int>& nums) {
    unordered_map<int, int> cnt;
    for (auto i : nums)
    {
        if (cnt.find(i) != cnt.end())
            cnt.erase(i);
        else
            cnt.insert(make_pair(i, 1));
    }
    return (*cnt.begin()).first;
}

去discuss中,发现还有更简单的解法,使用XOR位运算,因为A XOR A = 0,而且XOR具有结合性,所以A XOR B XOR C XOR A XOR C XOR B = 0

int singleNumber(vector<int>& nums) {
    int result = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        result ^= nums[i];
    }
    return result;
}
原文地址:https://www.cnblogs.com/sdlwlxf/p/5143278.html