您的位置:首页 > 其它

Single Number 【leetcode】1分钟解题系类

2014-09-21 22:39 316 查看
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?

这个题目是做过的,之前跟王子讨论过2个不同的数字。其它都是两对相同的时候,想到了位运算这种巧妙的算法。

异或运算:相同为0,不同为1。把所有的数字都异或一遍,相同的数字异或就约掉了,只剩下那个不同的数字了。

(秒解)

class Solution {
public:
    int singleNumber(int A[], int n) {
        int result = 0;
        for(int i=0;i<n;i++){
            result=result^A[i];
        }
        return result;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: