LeetCode136. 只出现一次的数字

一、题目描述

二、解法

class Solution {
    public int singleNumber(int[] nums) {
        /*Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        for (int n : map.keySet()) {
            if (map.get(n) == 1) {
                return n;
            }
        }
        throw new RuntimeException();*/
        /**
         *  要求:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
         *  思路:使用位运算解决,异或运算符的应用。时间复杂度O(n),空间复杂度O(1)
         *        1)交换律:a ^ b ^ c <=> a ^ c ^ b
         *        2)任何数与0异或为任何数 0 ^ n => n
         *        3)相同的数异或为0: n ^ n => 0
         *  举例:[2,3,2,4,4]
         *       2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3
         */
        int a = 0;
        for (int num : nums) {
            a ^= num;
        }
        return a;
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14117488.html