Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

因为所有数字都出现两次,只有一个出现一次,把所有的数字全部异或一次,就得到了single number

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

        for(int i = 1; i < nums.length; i++)
            res = res ^ nums[i];

        return res;
    }
}

results matching ""

    No results matching ""