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

[LeetCode] Single Number 单独的数字

时间:2014-11-29 14:30:53      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

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?

 

本来是一道非常简单的题,但是由于加上了时间复杂度必须是O(n),并且空间复杂度为O(1),使得不能用排序方法,也不能使用map数据结构。那么只能另辟蹊径,这个解法如果让我想,肯定想不出来,因为谁会想到用逻辑异或来解题呢。逻辑异或的真值表为:

 异或运算bubuko.com,布布扣真值表如下:

 

AB
F F F
F T T
T F T
T T F

由于数字在计算机是以二进制存储的,每位上都是0或1,如果我们把两个相同的数字异或,0与0异或是0,1与1异或也是0,那么我们会得到0。根据这个特点,我们把数组中所有的数字都异或起来,则每对相同的数字都会得0,然后最后剩下来的数字就是那个只有1次的数字。这个方法确实很赞,但是感觉一般人不会忘异或上想,绝对是为CS专业的同学设计的好题呀,赞一个~~ 

代码如下:

 

class Solution {
public:
    int singleNumber(int A[], int n) {
        int res = A[0];
        for (int i = 1; i < n; ++i) res ^= A[i];
        return res;
    }
};

 

[LeetCode] Single Number 单独的数字

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/grandyang/p/4130577.html

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