mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 350. Intersection of Two Arrays II.md
This commit is contained in:
parent
3240704a97
commit
436b38cabc
27
350. Intersection of Two Arrays II.md
Normal file
27
350. Intersection of Two Arrays II.md
Normal file
@ -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<int> intersect(vector<int>& nums1, vector<int>& nums2) {
|
||||
sort(nums1.begin(), nums1.end());
|
||||
sort(nums2.begin(), nums2.end());
|
||||
vector<int>res;
|
||||
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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user