349. Intersection of Two Arrays不重复的记录两个数组中共同的数字
来源:互联网 发布:软件测试各个阶段 编辑:程序博客网 时间:2024/05/16 09:26
计算两个数组中共同的数字,不能重复
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.
//解法1;将两个数组分别进行排序,用两个指针分别对其进行遍历——时间长class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> result; if(nums1.size()==0||nums2.size()==0) return result; sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); int i=0,j=0; while(i<nums1.size()&&j<nums2.size()) { if(nums1[i]==nums2[j]) { result.push_back(nums1[i]); while(i<nums1.size()&&nums1[i]==nums2[j]) i++; } else if(nums1[i]<nums[j]) i++; else if(nums[i]>nums[j]) j++; } return result; }};
//解法2:使用set数据结构,先遍历第一个数组,将其依次添加到set中(set本身就能保证数据不会重复),然后在其中依次找第二个数组中的数据,若找到了,就将其加到结果数组中,并将其从set中删除
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> nums; vector<int> intersection; for(auto n:nums1){ if(nums.find(n)==nums.end()) nums.insert(n); } for(auto n:nums2){ if(nums.find(n)!=nums.end()){ intersection.push_back(n); nums.erase(n); } } return intersection; }};
阅读全文
0 0
- 349. Intersection of Two Arrays不重复的记录两个数组中共同的数字
- 349. Intersection of Two Arrays (求两个数组的交集,不包含重复元素)
- 349. Intersection of Two Arrays | 找两个数组的交集
- 350. Intersection of Two Arrays II (求两个数组的交集,包含重复元素)
- [LeetCode] Intersection of Two Arrays 两个数组的交集
- Leetcode :Intersection of Two Arrays 两个数组的交集
- 350. Intersection of Two Arrays II | 查找两个数组重复
- [LeetCode]349. Intersection of Two Arrays(两数组的交集)
- leetcode 349. Intersection of Two Arrays 数组的交集
- 349. Intersection of Two Arrays 两个数组交集
- [easy]【leetcode】【java】 Intersection of Two Arrays II 两个数组的交集
- Leetcode Intersection of Two Arrays i,ii查找两个数组的公共元素
- leetcode-350 Intersection of Two Arrays II 求两个数组的交集 面试见到了吗?
- [LeetCode] Intersection of Two Arrays II 两个数组的交集II
- leetcode 350. Intersection of Two Arrays II 两个数组的交集
- Leetcode:350. Intersection of Two Arrays II 求两个数组的交集
- Intersection of Two Arrays--求两个向量的交集
- leetcode 记录 349. Intersection of Two Arrays
- 根据IP自动切换城市(腾讯网接口)
- BZOJ 3505: [Cqoi2014]数三角形 题解
- PHP的false与0
- GetBuffer解析
- 如何查看Tomcat是否安装配置成功
- 349. Intersection of Two Arrays不重复的记录两个数组中共同的数字
- PHP foreach循环
- java发送邮箱
- Shell脚本函数定义和函数参数
- 把二元查找树转变成排序的双向链表
- Struts2的数据验证框架validation framework
- IPC机制之AIDL实现客户端回调
- struts2编写自定义的验证程序
- python 3.5配置opencv