RE . 349. Intersection of Two Arrays
来源:互联网 发布:文字设计软件手机软件 编辑:程序博客网 时间:2024/05/16 09:36
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.
简单的 用排序
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> ans; //if((nums1.empty()) || (nums2.empty())) // return nums; 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]) { if(ans.empty()||nums1[i] != ans[ans.size()-1]) // 如果这里把ans.empty 放到||后面就会报错。 要先检测是否是空! ans.push_back(nums1[i]); ++i; ++j; } else nums1[i]<nums2[j]? i++:j++; } return ans; }};
看不懂的答案。。
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> m(nums1.begin(), nums1.end()); //这是啥 vector<int> res; for (auto a : nums2) if (m.count(a)) { res.push_back(a); m.erase(a); } return res; }};
0 0
- RE . 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
- android去掉滑动到顶部和底部的阴影
- ViewPager+Fragment多标题界面
- VS2015+QT5.7基础配置
- android xml 资源中各种符号的使用 @ ?
- log4j.xml的一般配置方式,补充说明.
- RE . 349. Intersection of Two Arrays
- 多线程基本知识
- 如何解决html中出现“​”
- 前端攻防篇-CSRF攻击及防御
- 洛谷 P2016 战略游戏
- @property (copy) NSMutableArray *array; 这个写法会出什么问题
- Qt修炼手册1_溢美之词和Designer设计
- 安装Office2007-sp3
- 一个初学者关于vr游戏开发的优化总结