Single Number

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

 

public class Solution {
    public int singleNumber(int[] A) {
        Arrays.sort(A);
        int size = A.length;
        for(int i=0;i<=size-3;i=i+2) {
            if(A[i]!=A[i+1]) return A[i];
        }
        return A[size-1];
    }
}

 后来发现用异或XOR竟如此简单:

public class Solution {
    public int singleNumber(int[] A) {
        int tmp = 0;
        int size = A.length;
        for(int i=0;i<size;i++) {
            tmp=tmp^A[i];
        }
        return tmp;
    }
}

 

posted @ 2015-03-19 13:40  mrpod2g  阅读(108)  评论(0编辑  收藏  举报