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:

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

    Example 2:

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

    题意

    给定一个非空数组,该数组中除了一个元素外,其余所有元素都出现了两次,找出该元素。

    思路

    使用136. Single Number (E) - 图1额外空间的方法很多,比如开散列、用Set计算和等。

    不使用额外空间的方法比较取巧,利用了异或位运算的性质:两个相同的数异或的结果为0。因此只要遍历所有元素进行异或,最后剩下的就是只出现了一次的元素。


    代码实现 - 位运算

    1. class Solution {
    2. public int singleNumber(int[] nums) {
    3. int ans = nums[0];
    4. for (int i = 1; i < nums.length; i++) {
    5. ans = ans ^ nums[i];
    6. }
    7. return ans;
    8. }
    9. }