1. 程式人生 > 實用技巧 >LeetCode136. 只出現一次的數字

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; } }