首页 > 其他 > 详细

[LeetCode] Single Number

时间:2017-07-10 17:26:07      阅读:138      评论: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?

给定一个数组,其中只有一个数字出现了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

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

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