Title Description:
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?
to complete the function:
vector<int> intersect (vector<int>& nums1, vector<int>& nums2)
Description:
1, the question given two vectors, requires the return of two vectors of the intersection, such as nums1=[1,2,2,1],nums2=[2,2], the return intersection is [2,2], how many of the same elements will return how many. The intersection of the returned is not order-conscious.
2, this problem read test instructions, familiar with Leetcode students should immediately think of the first sort, sorted after the two vector to compare, time complexity will fall a lot.
If it is not, it is a double-loop approach, O (n^2), and the complexity of the time is too high.
To sort and then compare the practice, the code is as follows: (with detailed)
vector<int> intersect (vector<int>& nums1, vector<int>& nums2) {sort (Nums1.begin ( ), Nums1.end ());//nums1 Sort, ascending sort (Nums2.begin (), Nums2.end ());//Nums2 sort, ascending int s1=nums1.size (), s2=nums2.size (), i=0,j=0;//i represents the position of the nums1 element, and J represents the position of the NUMS2 element vector<int>res;//the vector while storing the final result (i<s1&&j<s2 )//Two vectors once one has traversed, then the comparison {if (Nums1[i]<nums2[j]) {while (nums1[i]<nu MS2[J]&&I<S1)//Always find, until Nums1[i]>=nums2[j] i++; if (I==S1)//If I have reached the outside of NUMS1, then the end comparison is break; } else if (Nums1[i]>nums2[j]) {while (NUMS1[I]>NUMS2[J]&&J<S2)//always find, straight To Nums2[j]>=nums1[i] J + +; if (J==S2)//If J has reached the outside of NUMS2, then the end comparison is break; } if (Nums1[i]==nums2[j])//If just equal, then insert into res, update the values of I and J {Res. push_back (Nums1[i]); i++; j + +; }} return res; }
The above code is measured 7ms,beats 98.05% of CPP submissions.
Leetcode-350-intersection of two Arrays II (to find the intersection of two arrays)