LeeCode (Bitwise Operation) 136_Number that only appears once

LeeCode (Bitwise Operation) 136_Number that only appears once

Problem:
Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.

Description:

Your algorithm should have linear time complexity. Can you do it without using extra space?

Example 1:

Input: [2,2,1]
Output: 1
Example 2:

Input: [4,1,2,1,2]
Output: 4

Source: LeetCode
Link: https://leetcode-cn.com/problems/single-number
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:

The conventional solution to this problem is to use a set or hash table to store the numbers that appear, and finally traverse the set or hash table to get the numbers that only appear once.

In addition, you can use bit arithmetic to deal with this problem. First, let's look at the rules of bit arithmetic.

  1. Any number and 0 are XORed, and the result is still the original number, that is, a⊕0=a.
  2. Any number is XORed with itself, and the result is 0, that is, a⊕a=0.
  3. The exclusive OR operation satisfies the commutative and associative laws, that is, a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b.

Java code:

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

Guess you like

Origin blog.csdn.net/u013456390/article/details/112799493