LeetCode/349. Intersection of Two Arrays.md
2018-09-15 19:29:17 +08:00

32 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/)
# 思路
题目欲求两个数组的交集,注意集合里元素都是唯一的。可以考虑将两个数组进行排序,再用两个指针分别遍历两个有序数组,合理更新指针即可获取两个数组的重复元素。
为了没有重复的元素可以设置一个pre来记录上一个相同的元素是什么。
时间复杂度O(nlogn)
当然也可以用map来查看是否有相同元素。
# C++
```
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int>res;
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;
}
};
```