【leetcode】350. Intersection of Two Arrays II

  1. Intersection of Two Arrays II
    Given two arrays, write a function to compute their intersection.
    Example 1:
    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2,2]
    Example 2:
    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [4,9]
    说明
    输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
    可以不考虑输出结果的顺序。

【思路】
此题思路和349Intersection of Two Arrays 一样,只是这题不需要重复相同的数字要输出。
请参考 349.Intersection of Two Arrays
【代码】

代码1.暴力解法
class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        
        sort(nums1.begin(),nums1.end());
         sort(nums2.begin(),nums2.end());
         vector<int> result;
            int i =0 ,j=0;
            while( i < nums1.size()&& j < nums2.size() )
            {
                if(nums1[i] > nums2[j])
                    j++;
                else if(nums1[i] < nums2[j])
                       i++;
                      else 
                      {
                          int n= result.size();
                              result.push_back(nums1[i]);
                          i++;
                          j++;
                      }                    
            }
        return result;
    }
};

代码2,hash表法
class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 
        unordered_map< int ,int > re;
        vector<int> result;      
        for( int  i = 0; i < nums1.size();i++)
        {
            if(re.count(nums1[i])  )           
                re[nums1[i]]+=1;
            else
                 re[nums1[i]] =1;
        }
        for(int  i = 0; i < nums2.size();i++)
        {
            if(re.count(nums2[i]) && re[nums2[i]] )
               {
                re[nums2[i]]--;
                result.push_back(nums2[i]);
                }                     
        }        
      return result;          
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_42703504/article/details/84850362