『Leetcode』XOR XOR problem: 136. Numbers that appear only once

Table of contents

question

136. Numbers that occur only once

1. Idea

Initial idea: Hash table. The key records the array elements, and the value records the number of count occurrences. Space Complexity: O(n)
Improvement: XOR.

XOR property:
1. Any number and 0 do XOR operation, the result is still the original number, that is a⊕0=a
2. Any number and itself XOR operation, the result is 0, that is a⊕a=0
3. XOR operation satisfies commutative law and associative law, that is, a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b

2. Solutions

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        int res=0;
        for(int i:nums){
    
    
            res ^=i;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/JingYan_Chan/article/details/128138036