LeetCode--SingleNumber

Given an array of integers, every element appears twice except for one. Find that single one.

问题:

  给一个整数数组,除了一个是单独出现的,其他都是成对出现的,把这一个单独出现的找出来。

思路:

  对于每个数循环一遍数组比较查找肯定是可行的,但复杂度高效率低肯定超时,比如以下解法,复杂度O(n^2)

  

class Solution {
public:
    int singleNumber(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int i = 0, j = 0;
        int ans = 0;
        for(i = 0;i < n;i++)
        {
            for(j = 0;j < n;j++)
            {
                if(i == j)
                    continue;
                else if(A[i] == A[j])
                    break;
                    else continue;
            }
            
            if(j == n)
                return A[i];
        }
    }
};

  高效的解法是考虑把所有数异或,异或结果就是单独出现的数组。原理是:

  1.a^b=b^a

  2.a^a=0

  3.0^a=a

  所以例如:3^1^2^2^1^3^4=(1^1)^(2^2)^(3^3)^4=0^4=4 所以解法如下,复杂度O(n):

public class Solution {
    public int singleNumber(int[] A) {
        int result=0;
        for(int a:A){
            result = result^a;
        }
        return result;
        
    }
}

  

原文地址:https://www.cnblogs.com/zhoujunfu/p/4044967.html