【编程测试题】LeetCode single-number

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HelloZEX/article/details/82143571

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)空间

思路:相等的两个数异或为0,0与该唯一数异或为数字本身

 1.异或满足交换律。

2.相同两个数异或为0。

3.0异或一个数为那个数本身。

最后结果即出现1次的那个数。

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

猜你喜欢

转载自blog.csdn.net/HelloZEX/article/details/82143571