leetcode#136. Numbers that appear only once

Topic link

Title description:

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:

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

Problem-solving ideas

  Two ways of thinking, the first is very simple, just use a hash table to record the frequency of the array elements. The space complexity is O(n), what if you want to reduce it to O(1)?
  Understand the problem setting 除了某个元素只出现一次以外,其余每个元素均出现两次,, then think of a bit operation—— 异或.

About XOR:

  • If the two values ​​of a and b are not the same, the XOR result is 1. If the two values ​​of a and b are the same, the XOR result is 0 (assuming that a and b can only take 0 / 1)
  • a xor a = 0
  • b xor 0 = b
  • The exclusive OR operation satisfies the commutative law: a xor b xor a = (a xor a) xor b = b xor 0 = b

  Therefore, we can get the final result by accumulating the exclusive OR operation on the array. Because, result = nums[0] ^ nums[1] ^ nums[2] ^ nums[3] ^ ...XOR satisfies the commutative law so that the same two elements are calculated together first 0, then according to the problem setting, it can be known that in the end 0 ^ nums[i], nums[i] is the only array element with only one, which is the result.

Hash table

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        unordered_map<int,int> record;
        for(int i = 0; i < nums.size(); i++){
    
    
            record[nums[i]]++;
        }

        for(auto iter = record.begin(); iter != record.end(); iter++){
    
    
            if(iter->second == 1){
    
    
                return iter->first;
            }
        }

        throw "wrong input";
    }
};

Bit operation

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        int result = nums[0];
        for(int i = 1; i < nums.size(); i++)
            result = result ^ nums[i];
        return result;
    }
};

If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io

Guess you like

Origin blog.csdn.net/weixin_40807714/article/details/104866007