349. Intersection of Two Arrays。
来源:互联网 发布:linux arch 编辑:程序博客网 时间:2024/06/16 19:10
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
这个题比较简单,两个集合求交集,如果有多个元素只需要保存一个即可。可以使用set来存放结果,最后转换成vector即可。而且因为要求结果可以是无序的,所以使用unordered_set的话可能要比set快一点。
#include <iostream>#include <vector>#include <unordered_map>#include <unordered_set>using namespace std;class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> result; unordered_set<int> temp(nums1.begin(),nums1.end());//将num1转换成set。 for(auto num : nums2) { if(temp.count(num)) result.insert(num);//如果temp中已经有了这个元素则存放在result中 } return vector<int>(result.begin(),result.end()); }};int main() { Solution s; vector<int> v1 = {1,2,3,1}; vector<int> v2 = {1,1}; vector<int> res = s.intersect(v1,v2); for(int num : res) { cout << num << endl; }}
阅读全文
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- Maven中的参数分别是什么意思?
- MacBook搭建服务器环境
- 542. 01 Matrix 寻找最近的0 重点 BFS 动态规划
- 在CENTOS7上玩转Ethereum区块链(2):Ethereum搭建篇
- 基础概念:Oracle数据库、实例、用户、表空间、表之间的关系
- 349. Intersection of Two Arrays。
- 建造者模式
- BZOJ1050 旅行comf
- (转载)Linux 学习记录 二 (文件的打包压缩)
- 如何用REDIS实现分布式缓存
- 如何删除虚拟机的虚拟网卡
- react脱离JXS
- 关于OOM
- 289. Game of Life