350.Intersection of Two Arrays II
Given two integer arrays nums1
and nums2
, return an array of their intersection . Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order .
Example 1:
1 2 Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
1 2 3 Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted.
双指针:
时间复杂度:O(mlogm+nlogn)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution {public : vector<int > intersect (vector<int >& nums1, vector<int >& nums2) { sort (nums1.begin (), nums1.end ()); sort (nums2.begin (), nums2.end ()); int length1 = nums1.size (), length2 = nums2.size (); int index1 = 0 , index2 = 0 ; vector<int > intersection; while (index1 < length1 && index2 < length2) { int num1 = nums1[index1], num2 = nums2[index2]; if (num1 == num2) { intersection.push_back (num1); index1++; index2++; } else if (num1 < num2) { index1++; } else { index2++; } } return intersection; } };
哈希表:
时间复杂度:O(m+n)
空间复杂度:O(min(m,n))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution {public : vector<int > intersect (vector<int >& nums1, vector<int >& nums2) { if (nums1.size () > nums2.size ()) { return intersect (nums2, nums1); } unordered_map <int , int > m; for (int num : nums1) { ++m[num]; } vector<int > intersection; for (int num : nums2) { if (m.count (num)) { intersection.push_back (num); --m[num]; if (m[num] == 0 ) { m.erase (num); } } } return intersection; } };