350. Intersection of Two Arrays II
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.
求两个集合的交集
C++(9ms):
1 class Solution { 2 public: 3 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 unordered_map<int,int> Map ; 5 vector<int> res ; 6 for(int i = 0 ; i < nums1.size() ; i++){ 7 Map[nums1[i]]++ ; 8 } 9 for(int i = 0 ; i < nums2.size() ; i++){ 10 if (--Map[nums2[i]] >= 0) 11 res.push_back(nums2[i]) ; 12 } 13 return res ; 14 } 15 };
C++(9ms):
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 ; 8 int j = 0 ; 9 while(i < nums1.size() && j < nums2.size()){ 10 if (nums1[i] == nums2[j]){ 11 res.push_back(nums1[i]) ; 12 i++ ; 13 j++ ; 14 }else if (nums1[i] > nums2[j]){ 15 j++; 16 }else{ 17 i++ ; 18 } 19 } 20 return res ; 21 } 22 };