[LeetCode]349. Intersection of Two Arrays
来源:互联网 发布:mac版qq接收文件 编辑:程序博客网 时间:2024/05/21 08:45
Intersection of Two Arrays
- 问题描述
- 代码
- 代码分析
- 其他解法
问题描述
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
代码
#include <algorithm>#include <iostream>#include <vector>#include <set>using namespace std;class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); set<int> tmp; int p1 = 0; int p2 = 0; while(p1 < (int)nums1.size() && p2 < (int)nums2.size()) { if(nums1[p1] == nums2[p2]) { tmp.insert(nums1[p1]); p1++; p2++; } else if(nums1[p1] > nums2[p2]) p2++; else p1++; } int n = tmp.size(); vector<int> nums3(n); copy(tmp.begin(),tmp.end(),nums3.begin()); return nums3; }};
代码分析
此题要求寻找两个数的交集,并且最后的vector容器不能有重复元素。
我的想法就是直接用set容器保存,这样就不可能有重复元素。
然后再转换成vector。
然后自己还是太naive了,copy()函数得准确使用
copy(begin,end,container.begin());//被复制的容器需事先分配足够的空间,不然无法复制进去
其他解法
可以到下述网址查看
https://leetcode.com/problems/intersection-of-two-arrays/discuss/
阅读全文
0 0
- leetcode 记录 349. Intersection of Two Arrays
- 349.[Leetcode]Intersection of Two Arrays
- [leetcode] 349. Intersection of Two Arrays
- Leetcode Everyday: 349. Intersection of Two Arrays
- leetcode.349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- 【leetcode】 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode题解 349. Intersection of Two Arrays
- LeetCode - 349. Intersection of Two Arrays
- [Leetcode]349. Intersection of Two Arrays
- 349. Intersection of Two Arrays--LeetCode Record
- LeetCode 349. Intersection of Two Arrays
- 8张图理解Java
- 如何得到你想要的东西
- 编程作业 50 2题 编写一个程序求100以内的全部素数
- Linux教程【10】- 压缩解压命令
- 无人机驾驶员培训学习记录(六)
- [LeetCode]349. Intersection of Two Arrays
- 深拷贝、浅拷贝
- 2017
- SDUT-2676 3-7 类的友元函数的应用
- Maven多项目
- eclipse中git pull拉取报错Checkout conflict with files
- Codeforces-258C:Little Elephant and LCM(数论)
- java_se 抽象类(包含多态知识)
- 【BZOJ1010】【HNOI2008】玩具装箱