The use of C++ set and map-(the intersection of the two arrays of leetcode)

Both set and map are associative containers. They are usually built-in language standard libraries. They have the following operations:

insert

s.insert()

Find

if(s.find(nums2[i]) != s.end())    //找到的情况

delete

s.erase(10)        //删除10号元素

Modify change (map exclusive)

set has the following characteristics

  • All elements have only key and no value
  • Do not allow duplicate values
  • All elements will be sorted automatically
  • The value of the set cannot be changed through the iterator, because the value of the set is the key, but it can be accessed

leetcode topic

Given two arrays, write a function to calculate their intersection.

Example

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

Code

#include<iostream>
#include<vector>
#include<set>

class Solution {
    
    
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    
    
        set<int> record;
        for(int i=0; i<nums1.size(); i++){
    
    
            record.insert(nums1[i]);
        }
        set<int> result;
        for(int i=0; i<nums2.size(); i++){
    
    
            if(record.find(nums2[i]) != record.end())
                result.insert(nums2[i]);
        }
        vector<int> res;
        //使用迭代器访问set
        for(set<int>::iterator iter = result.begin(); iter != result.end(); iter++)
            res.push_back(*iter);
        return res;
    }
};

Map has the following characteristics

  • All elements are keys + values ​​exist
  • The key is not allowed to be repeated, the key will have a corresponding value
  • The key of the map cannot be modified, but the value corresponding to the key can be modified

map traversal key value

map<int, int> record;
for(map<int>::iterator iter = record.begin(); iter != record.end(); iter++){
    
    
        //first是键, second是值
        cout<<iter->first<<" "<<iter->second<<endl;
}

leetcode topic

Given two arrays, write a function to calculate their intersection. The array elements may be duplicated.

Example

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]

Code

#include<iostream>
#include<vector>
#include<map>

class Solution {
    
    
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    
    
        map<int, int> record;
        for(int i=0; i<nums1.size(); i++)
            record[nums1[i]]++;
        
        vector<int> res;
        for(int i=0; i<nums2.size(); i++){
    
    
            if(record[nums2[i]] > 0){
    
    
                res.push_back(nums2[i]);
                record[nums2[i]]--;
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/UCB001/article/details/106840586