leetcode / 136 only appears once

Recently, the epidemic situation brushed water at home. This problem is to find the number
that appears only once in the array. The time complexity is O (n), and no new space is stored.
Title: The number
that appears only once has been done once on the Jianzhi Offer, it is sorted, and then whoever has only one number is clear at a glance.
But the time complexity is O (logN + N).

The idea this time is to use XOR operation. The important concepts of XOR operation are as follows (where N is any number):

  1. 0 xor N = N
  2. N xor N = 0
  3. The XOR operation satisfies the exchange law and the combination law
    , namely: a xor b xor a = (a xor a) xor b = 0 xor b = b

So when you see this, you suddenly feel ashamed and record ashamed ...

class Solution {
    public int singleNumber(int[] nums) {
        int xor = 0;
        for(int i: nums){
            xor ^= i;
        }
        return xor;
    }
}
Published 263 original articles · 110 praises · 120,000 views

Guess you like

Origin blog.csdn.net/rikkatheworld/article/details/104134259