【LeetCode 136】 关关的刷题日记34 Intersection of Two Arrays II

时间:2022-05-07
本文章向大家介绍【LeetCode 136】 关关的刷题日记34 Intersection of Two Arrays II,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记34 – Leetcode 350. Intersection of Two Arrays II

题目

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

Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.

题目的意思是给定两个数组,求这两个数组的交集,与349的区别是,这次两个数组中重复的数字都要求体现出来。

思路

思路:由于重复的数字都要求体现出来,所以要建map来存这些数,key存数组中的数,value用来计数。

class Solution {
  public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<int,int>m;
        vector<int>output;
        for(int x:nums1)
        {
            m[x]++;
        }
        for(int y:nums2)
        {
            if(m.find(y)!=m.end())
            {
                if(m[y]>0)
                {
                    m[y]--;
                    output.push_back(y);     
                }
            }               
        }
        return output;

    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。