Intersection of Arrays II
- Total accepted:23510
- Total submissions:56283
- Difficulty:easy
Given the arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
- Each element of the result should appear as many times as it shows in both arrays.
- The result can be on any order.
Follow up:
- What if the given array is already sorted? How would optimize your algorithm?
- What if nums1' s size is small compared to nums2' s size? Which algorithm is better?
- What if elements of nums2 be stored on disk, and the memory is limited such so you cannot load all elements in To the memory at once?
Idea: and Leetcode 349. Intersection of the arrays similar, but note the difference of the return value.
In addition, I learned the usage of unordered_set and unordered_map .
Code:
Method One: Using Unordered_map, the complexity is lower than the method two.
1 classSolution {2 Public:3vector<int> Intersect (vector<int>& Nums1, vector<int>&nums2) {4unordered_map<int,int>m;5vector<int>Res;6 for(intI:NUMS1) m[i]++;7 for(inti:nums2) {8 if(m[i]-->0){9 Res.push_back (i);Ten } One } A returnRes; - } -};
Method Two:
1 classSolution {2 Public:3vector<int> Intersect (vector<int>& Nums1, vector<int>&nums2) {4 sort (Nums1.begin (), Nums1.end ());5 sort (Nums2.begin (), Nums2.end ());6vector<int>Res;7 intI=0, j=0;8 while(I<nums1.size () &&j<nums2.size ()) {9 //while (I+1<nums1.size () &&nums1[i]==nums1[i+1]) i++;//Remove duplicate elementsTen //while (J+1<nums2.size () &&nums2[j]==nums2[j+1]) j + +; One if(nums1[i]==Nums2[j]) { A Res.push_back (Nums2[j]); -i++; -J + +; the } - Else{ -nums1[i]>nums2[j]?j++:i++; - } + } - returnRes; + } A};
Leetcode 350. Intersection of Arrays II