Leetcode 350. Intersection of Two Arrays II

350. Intersection of Two Arrays II

  • Total Accepted: 23510
  • Total Submissions: 56283
  • Difficulty: Easy

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.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

思路:和Leetcode 349. Intersection of Two Arrays类似,但注意返回值的区别。

另外学习了unordered_setunordered_map的用法。

代码:

方法一:利用unordered_map,复杂度比方法二低。

 1 class Solution {
 2 public:
 3     vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
 4         unordered_map<int,int> m;
 5         vector<int> res;
 6         for(int i:nums1) m[i]++;
 7         for(int i:nums2){
 8             if(m[i]-->0){
 9                 res.push_back(i);
10             }
11         }
12         return res;
13     }
14 };

方法二:

 1 class Solution {
 2 public:
 3     vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
 4         sort(nums1.begin(),nums1.end());
 5         sort(nums2.begin(),nums2.end());
 6         vector<int> res;
 7         int i=0,j=0;
 8         while(i<nums1.size()&&j<nums2.size()){
 9             //while(i+1<nums1.size()&&nums1[i]==nums1[i+1]) i++;//去除重复元素
10             //while(j+1<nums2.size()&&nums2[j]==nums2[j+1]) j++;
11             if(nums1[i]==nums2[j]){
12                 res.push_back(nums2[j]);
13                 i++;
14                 j++;
15             }
16             else{
17                 nums1[i]>nums2[j]?j++:i++;
18             }
19         }
20         return res;
21     }
22 };
原文地址:https://www.cnblogs.com/Deribs4/p/5728223.html