Description
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.Follow up:What if the given array is already sorted? How would you optimize your algorithm?What if nums1's size is small compared to nums2's size? Which algorithm is better?What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?My solution
延续leetcode 344的思路,少做修改即可, 但是复杂度仍旧很高啊...
class Solution {public: vector intersect(vector &nums1, vector &nums2) { vector res; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int 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 { while (nums1[i] == nums2[j] && i < nums1.size() && j < nums2.size()) { res.push_back(nums1[i]); ++i; ++j; } while (nums1[i] == nums1[i - 1]) ++i; while (nums2[j] == nums2[j - 1]) ++j; } } return res; }};
Discuss
sort
Time: O(max(m, n) log(max(m, n)))
但我又不得不说, 同样是sort方式, 我的方案太丑!!
discuss中同样方法的代码如下:class Solution {public: vector intersect(vector & nums1, vector & nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int n1 = (int)nums1.size(), n2 = (int)nums2.size(); int i1 = 0, i2 = 0; vector res; while(i1 < n1 && i2 < n2){ if(nums1[i1] == nums2[i2]) { res.push_back(nums1[i1]); i1++; i2++; } else if(nums1[i1] > nums2[i2]){ i2++; } else{ i1++; } } return res; }};
注意, 只用了一次while! 逻辑很清晰!
Hash table solution
Time: O(m + n) Space: O(m + n)
class Solution {public: vector intersect(vector & nums1, vector & nums2) { unordered_mapdict; vector res; for(int i = 0; i < (int)nums1.size(); i++) dict[nums1[i]]++; for(int i = 0; i < (int)nums2.size(); i++) if(--dict[nums2[i]] >= 0) res.push_back(nums2[i]); return res; }};
采用unordered_map查询效率高, 无序.