您的位置:首页 > 其它

[LeetCode]Single Number

2014-06-26 22:46 323 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: