Likou——Numbers that only appear once ⅠⅡⅢ(C++)

1 topic description

Insert picture description here
Insert picture description here
Insert picture description here

The topic link is as follows:
https://leetcode-cn.com/problems/single-number/
https://leetcode-cn.com/problems/single-number-ii/
https://leetcode-cn.com/problems/ single-number-iii/

2 Problem analysis and realization

2.1 Topic 1

2.1.1 Analysis

In addition to an array element appears only once, the other elements are present twice, then you can turn to exclusive or elements within the array, the same number of
words to be exclusive or become 0, the final result is the emergence of XOR Numbers at a time.

2.1.2 Implementation

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

2.2 Topic 2

2.2.1 Analysis

32 times each bit of the digital count for each position in the array 1 appears, if the number 1 appears 3 * n + 1 is the array so that appear only once in
a 32-bit number corresponding bit is 1, The other bits are 0. This number can be deduced from this rule. You only need to set the position of 1 to 1, and the
other positions to 0 to find this number.

2.2.2 Implementation

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        //统计vector中的每个数字32位,1的个数放进数组里,若出现1的次数是3*n+1,那么题中所求的数对应的位就是1,,其他位是0,
        //就可以反推出要求的数
        //1、统计所有数字32个位1出现的次数
        int bitArray[32]={
    
    0};
        for(auto x:nums){
    
    
            for(size_t i = 0;i<32;i++){
    
    
                if(x & (1<<i)){
    
    
                    bitArray[i]++;
                }
            }
        }
        //2、分离出这个数字用 |=
        int ret = 0;
        for(size_t i = 0;i<32;i++){
    
    
            if(bitArray[i]%3==1){
    
    
                ret |= (1<<i);
            }
        }
        
        return ret;
    }
};

2.3 Topic 3

Reference: https://blog.csdn.net/CZHLNN/article/details/113447046

Guess you like

Origin blog.csdn.net/CZHLNN/article/details/113785860