mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
32 lines
1.2 KiB
Markdown
32 lines
1.2 KiB
Markdown
![]() |
# [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;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|