diff --git a/349. Intersection of Two Arrays.md b/349. Intersection of Two Arrays.md new file mode 100644 index 0000000..0027315 --- /dev/null +++ b/349. Intersection of Two Arrays.md @@ -0,0 +1,31 @@ +# [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/) +# 思路 +题目欲求两个数组的交集,注意集合里元素都是唯一的。可以考虑将两个数组进行排序,再用两个指针分别遍历两个有序数组,合理更新指针即可获取两个数组的重复元素。 +为了没有重复的元素,可以设置一个pre来记录上一个相同的元素是什么。 +时间复杂度O(nlogn) +当然也可以用map来查看是否有相同元素。 +# C++ +``` +class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + vectorres; + int p1 = 0, p2 = 0, pre; + while(p1 < nums1.size() && p2 < nums2.size()){ + if(nums1[p1] < nums2[p2]) p1++; + else if(nums1[p1] > nums2[p2]) p2++; + else{ + if(res.empty() || pre != nums1[p1]){ + res.push_back(nums1[p1]); + pre = nums1[p1]; + } + p1++; + p2++; + } + } + return res; + } +}; +```