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

[LeetCode] Single Number

时间:2017-07-10 18:02:09      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:ber   out   turn   code   with   ext   cto   class   eve   

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

 

[LeetCode] Single Number

标签:ber   out   turn   code   with   ext   cto   class   eve   

原文地址:http://www.cnblogs.com/immjc/p/7146616.html

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