[LeetCode] 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次。求出这个出现一次的数字。这道题利用XOR进行求解,如果两个数字相同,那么它们的XOR为0,然而0与任何数XOR都是任何数。所以用0与数组中各个数XOR,最后的结果就是那个只出现一次的数字。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for (int num : nums)
            res ^= num;
        return res;
    }
};
// 13 ms

 

posted @ 2017-07-10 16:48  immjc  阅读(145)  评论(0编辑  收藏  举报