题目

image.png

思路

  1. 交换律:a ^ b ^ c <=> a ^ c ^ b
  2. 任何数于0异或为任何数 0 ^ n => n
  3. 相同的数异或为0: n ^ n => 0

    代码

    1. public int singleNumber(int[] nums) {
    2. if (nums.length == 0) return 0;
    3. int res = nums[0];
    4. for (int i = 1; i < nums.length; i++) {
    5. res = res ^ nums[i];
    6. }
    7. return res;
    8. }
    只出现一次的数字