您的位置:首页 > 其它

Single Number -- leetcode

2015-05-29 15:55 423 查看
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?

基本思路:

利用异或运算。

一个数和自己异或结果为0.

0和一个数异或,则为该数。

由于数组中,每个数,都会出现两遍。只有一个数例外。

则对该数组元素全体作完异或后,结果为那个例外的数。 因为其他数都互相抵消了。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for (int i=0; i<nums.size(); i++) {
            ans ^= nums[i];
        }
        return ans;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: