面试题:找出数组中只出现一次的数字

难度:中等

一个整数数组,除了一个数之外所有数字都出现了2次,找出这个数字来。

注意: 你的算法应该是线性运行复杂度,且不能使用额外内存空间。

 

答案:

public class Solution {
    public int singleNumber(int[] nums) {
        int n =0;

        // as we know that bitwise XOR in Java
        // 0 ^ N = N
        // N ^ N = 0
        for(int i=0; i!=nums.length; i++) {
            n ^= nums[i];
        }

        return n;
    }
}

 

posted @ 2015-08-27 22:35  -小城-  阅读(132)  评论(0编辑  收藏  举报