标签:data static float text should font 实现 als tar
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
Follow up:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public : vector< int > intersect(vector< int >& nums1, vector< int >& nums2) { multiset< int > set1(nums1.begin(), nums1.end()); multiset< int > set2(nums2.begin(), nums2.end()); vector< int > result; vector< int > & nums = nums1.size() > nums2.size() ? nums2 : nums1; // nums equals to the shorter array for (auto n : nums){ int a = set1.erase(n); // find the count of n in nums1 int b = set2.erase(n); // find the count of n in nums2 if ( a && b){ int time = min(a,b); while ( time --) result.push_back(n); } } return result; } }; |
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : vector< int > intersect(vector< int >& nums1, vector< int >& nums2) { vector< int > result(nums1.size() + nums2.size()); sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto it = set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), result.begin()); result.resize(it - result.begin()); return result; } }; |
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 | class Solution { public : vector< int > intersect(vector< int >& nums1, vector< int >& nums2) { vector< int > result(nums1.size() + nums2.size()); int i = 0; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto l1 = nums1.begin(), r1 = nums1.end(); auto l2 = nums2.begin(), r2 = nums2.end(); while (l1 < r1 && l2 < r2){ if (*l1 < *l2){ ++l1; } else if (*l1 > *l2){ ++l2; } else { result[i++] = *l1; ++l1; ++l2; } } result.resize(i); return result; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public : vector< int > intersect(vector< int >& nums1, vector< int >& nums2) { unordered_map< int , int > mymap; vector< int > result; for (auto n: nums1){ ++mymap[n]; } for (auto n: nums2){ if (mymap[n]-- > 0){ result.push_back(n); } } return result; } }; |
350. Intersection of Two Arrays II
标签:data static float text should font 实现 als tar
原文地址:http://www.cnblogs.com/zhxshseu/p/56a44a725b01fc5e0780b45f35ad01b6.html