Sword Finger Offer Interview Question 56-I. Number of occurrences of numbers in the array [Medium]-unordered_map

My solution:

Use unordered_map

Traverse the array, add the map before the element appears, erase it when it appears, and finally return the remaining two numbers

But this does not meet the requirements of space complexity

class Solution {
public:
    vector<int> singleNumbers(vector<int>& nums) {
        unordered_map<int,int> m;
        vector<int> res;
        for(int i=0;i<nums.size();i++){
            if(m.count(nums[i]))    m.erase(nums[i]);
            else m[nums[i]]=1;
        }
        unordered_map<int,int>::iterator it;
        it=m.begin();
        res.push_back(it->first);
        it++;
        res.push_back(it->first);
        return res;
    }
};

Some bigwigs use XOR operations, and I will come back later. . .

 

Published 65 original articles · Like1 · Visits 489

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105454691