[LeetCode]Single Number

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?

Analysis:

The requirement is O(n) time and O(1) space.
Thus, the "first sort and then find " way is not working.
Also the "hash map" way is not working.

Since we can not sort the array, we shall find a cumulative way, which is not about the ordering.

XOR (Exclusiove Or) is a good way, we can use the property that A XOR A = 0, and A XOR B XOR A = B.

So, the code becomes extremely easy.

Java

public int singleNumber(int[] A) {
        int result = A[0];
        for(int i=1;i<A.length;i++){
        	result = result^A[i];
        }
        return result;
    }

c++

int singleNumber(int A[], int n) {
    int result = A[0];
    for(int i=1;i<n;i++){
        result = result ^ A[i];
    }
    return result;
}





你可能感兴趣的:(LeetCode,XOR)