[One question per day] 22: Numbers that appear only once (summary answers to questions)

Title one description

Given a non-empty integer array, except that an element appears only once, each 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:

输入: [2,2,1]
输出: 1

Problem code

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

Topic 2 description

Given a non-empty integer array, except that an element appears only once, every other element appears three times. 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:

输入: [2,2,3,2]
输出: 3

Problem code

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int sz = nums.size();

        int sum = 0;
        
        for(int i = 0; i < 32; ++i){
            int count = 0;
            for(auto j : nums){
                count += j >> i & 1;
            }
            if(count % 3){
                sum += 1 << i;
            }
        }
        
        /*int sum = 0, tmp = 0;
		for (auto &i : nums)
		{
			sum = (sum ^ i) & ~tmp;
			tmp = (tmp ^ i) & ~sum;
		}*/
		
        return sum;
    }
};

Topic three description

Given an integer array nums, there are exactly two elements that appear only once, and all other elements appear twice. Find the two elements that appear only once.

Example:

输入: [1,2,1,3,2,5]
输出: [3,5]

Problem code

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

        //就是保留sum的最后一个1,并且将其他位变为0(记录其大小)
        int k = sum & (-sum); 

        vector<int> num(2, 0);
        for(auto i : nums){
            if(i & k){
                num[0] ^= i;
            }
            else{
                num[1] ^= i;
            }
        }
        
        return num;
    }
};

If you have different opinions, please leave a message to discuss!

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105168911