码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number -- leetcode

时间:2015-05-29 18:16:19      阅读:142      评论:0      收藏:0      [点我收藏+]

标签: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?


基本思路:

利用异或运算。

一个数和自己异或结果为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;
    }
};


Single Number -- leetcode

标签:leetcode   异或   

原文地址:http://blog.csdn.net/elton_xiao/article/details/46237339

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!