首页 > 其他 > 详细

Single Number -- leetcode

时间:2015-05-29 18:13:46      阅读:224      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!