Given an array, look for the number that appears only once in the array (Likou 136)

  1. Numbers that appear only once
    Given a non-empty integer array, except for one 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

-Hash

Recently I was learning about the hash data structure. The first reaction was to use the hash table to count. After traversing the array, the hash is traversed to find the element with the number of occurrences of 1. The time complexity is O(N), and the space complexity is O ( N)

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
     unordered_map<int, int> hash;//key值为元素值,val放出现次数
        int len = nums.size();
        for (int i = 0; i < len; i++) {
    
    
            unordered_map<int, int>::iterator it = hash.find(nums[i]);
            if (it == hash.end())//哈希表中无该数
                hash[nums[i]] = 1;//将该数的val置1
            else {
    
    
                hash[nums[i]]++; //若已经存在,val加一
            }
        }
        for (auto val : hash) {
    
    //将hash表中所有数据进行遍历,寻找出现次数为1的元素
            if (val.second == 1)
                return val.first;
        }
        return 0;
    }
};

-Bit Operation After
reading the solution of the problem, I remembered that there is another subtle operation: exclusive OR, the same is false but the difference is true, the specific operation is as follows:

Commutative law: a ^ b ^ c <=> a ^ c ^ b

XOR any number at 0 is any number 0 ^ n => n

The XOR of the same number is 0: n ^ n => 0
For example:
Insert picture description here

var a = [2,3,2,4,4]
2 ^ 3 ^ 2 ^ 4 ^ 4 is equivalent to 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
     int ans=0;
     for(auto num:nums)
        ans^=num;
        
        return ans;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/Genius_bin/article/details/113103176