diff --git a/350. Intersection of Two Arrays II.md b/350. Intersection of Two Arrays II.md new file mode 100644 index 0000000..ff1af5c --- /dev/null +++ b/350. Intersection of Two Arrays II.md @@ -0,0 +1,27 @@ +# [350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/description/) +# 思路 +基本同[349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/), 只是题结果中可以出现重复元素, +则先对两个数组进行排序,然后再用两个指针遍历一遍数组,合理更新指针即可获得两个数组的相同元素。 +时间复杂度O(nlogn) +# C++ +``` +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + vectorres; + int p1 = 0, p2 = 0; + while(p1 < nums1.size() && p2 < nums2.size()){ + if(nums1[p1] < nums2[p2]) p1++; + else if(nums1[p1] > nums2[p2]) p2++; + else{ + res.push_back(nums1[p1]); + p1++; + p2++; + } + } + return res; + } +}; +```