Intersection of Two Arrays II – LeetCode 350
Problem
Description
Given two arrays, write a function to compute their intersection.
Example
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Answer
Original
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> result; sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); unsigned i = 0, j = 0; while(i != nums1.size() && j != nums2.size()){ if(nums1[i] < nums2[j]) ++i; else if(nums1[i] > nums2[j]) ++j; else { result.push_back(nums1[i]); ++i; ++j; } } return result; } };
|
思路
优先排序然后进行遍历检查,时间复杂度$O(nlog{n})$,空间复杂度$O(1)$。
耗时$7$ ms,排名$72.80\%$
Better
思路
使用hashmap存储出现的次数,用空间换时间,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$7$ ms,排名$72.80\%$
Code
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> m; vector<int> res; for (auto a : nums1) ++m[a]; for (auto a : nums2) if (m[a]-- > 0) res.push_back(a); return res; } };
|