Leetcode 349. Intersection of Two Arrays
来源:互联网 发布:冲压模具设计软件 编辑:程序博客网 时间:2024/06/14 03:01
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.
思路:遍历nums1,如果找到nums2里没有的元素就删除,最后再遍历一次nums1,删除重复的元素。
#include<cstdio>#include<vector>#include<algorithm>using namespace std;/***********************************************提交部分******************************************************/ class Solution{public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2){for(vector<int>::iterator p=nums1.begin(); p!=nums1.end(); ){if(find(nums2.begin(),nums2.end(),*p)==nums2.end())//如果在nums1里找到nums2中没有的元素则删除 {vector<int>::iterator p1=p;p=nums1.erase(p1);}elsep++;}for(vector<int>::iterator p=nums1.begin(); p!=nums1.end();)//删除nums1里重复的元素 {if(find(nums1.begin(),nums1.end(),*p)!=nums2.end()&&find(nums1.begin(),nums1.end(),*p)!=p){vector<int>::iterator p1=p;p=nums1.erase(p1);}elsep++;}return nums1;}};/***************************************************************************************************************/int main(){int n,m;vector<int> a,b,ans;while(scanf("%d%d",&n,&m)==2){int tmp;a.clear();b.clear();ans.clear();for(int i=0; i<n; i++){scanf("%d",&tmp);a.push_back(tmp);}for(int i=0; i<m; i++){scanf("%d",&tmp);b.push_back(tmp);}Solution s;ans=s.intersection(a,b);for(int i=0; i<ans.size(); i++)printf("%d ",ans[i]);printf("\n");}return 0;}
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
- Kd-tree的用法
- 如何让一个ListVIew按类型显示多种Item视图
- 文件的读取写入
- Java设计模式—代理模式
- 欢迎使用CSDN-markdown编辑器
- Leetcode 349. Intersection of Two Arrays
- 面试时说的Android消息机制
- 网络流24题——太空飞行计划问题
- IntelliJ IDEA - 热部署插件JRebel 安装使用教程
- 使用UITextView想看下视图层次出错,解决方法
- iOS UITableViewCell 的 imageView大小更改
- 【置顶】Android启动页面有白屏(或者黑屏)过渡解决方案
- 消息推送
- HHU Kingdom of Black and White(暴力搜索+线段树)