349.Intersection of Two Arrays
Given two integer arrays nums1
and nums2
, return an array of their intersection . Each element in the result must be unique and you may return the result in any order .
Example 1:
1 2 Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
1 2 3 Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted.
哈希表:
时间复杂度:O(n+m)
空间复杂度:O(n+m)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution {public : vector<int > intersection (vector<int >& nums1, vector<int >& nums2) { vector<int > ans; unordered_set<int > set1; unordered_set<int > set2; for (int num : nums1)set1.insert (num); for (int num : nums2)set2.insert (num); if (set1.size () > set2.size ())swap (set1, set2); for (int num : set1) { if (set2.count (num))ans.push_back (num); } return ans; } };
双指针:
时间复杂度:O(nlogn+mlogm)
空间复杂度:O(nlogn+mlogm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution {public : vector<int > intersection (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) { if (!intersection.size () || num1 != intersection.back ()) { intersection.push_back (num1); } index1++; index2++; } else if (num1 < num2) { index1++; } else { index2++; } } return intersection; } };