您的位置:首页 > 其它

Leetcode NO.136 Single Number

2015-09-22 06:21 204 查看
本题题目要求如下:

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和一个数字异或,结果为该数字。。所以可以写出一下的代码:
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for (int i = 0; i < nums.size(); ++i) {
            res ^= nums[i];
        }
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: