leetcode 349. Intersection of Two Arrays
来源:互联网 发布:淘宝上代写代发论文 编辑:程序博客网 时间:2024/06/06 04:25
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) { sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); int i=0,j=0; vector<int> ret; while(i<nums1.size()&&j<nums2.size()) { if(nums1[i]==nums2[j]) { if(ret.back()!=nums1[i]) ret.push_back(nums1[i]); i++; j++; } while(nums1[i]<nums2[j]) i++; while(nums2[j]<nums1[i]) j++; } return ret; }};runtime error
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { std::sort(nums1.begin(), nums1.end()); std::sort(nums2.begin(), nums2.end()); vector<int> ans; int i = 0, j = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) i++; else if (nums1[i] > nums2[j]) j++; else { if (!ans.size() || ans.back() != nums1[i]) ans.push_back(nums1[i]); i++; j++; } } return ans; }};
accepted???
这两个代思想上一样,为什么一个runtimeerro一个AC?
while(nums1[i]<nums2[j]) i++; while(nums2[j]<nums1[i]) j++;并没有检查是否越界,而if ... else if ... else在每一次判定后都进行了检查。
使用set 的code:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s(nums1.begin(), nums1.end()); vector<int> out; for (int x : nums2) if (s.erase(x)) out.push_back(x); return out;}
class Solution {public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> st1(nums1.begin(),nums1.end()); unordered_set<int> st2(nums2.begin(),nums2.end()); vector<int> ret; for(const auto & x:st1) if(st2.count(x)) ret.push_back(x); return ret;}};
阅读全文
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
- Java web开发中的各种bean对应的术语(VO,PO,BO,QO, DAO,POJO,DTO)
- Eclipse的使用简介
- JavaWeb三大组件之一Servlet【访问量统计-ServletContext的应用】
- arcgis servie10.3 发布缓存服务
- Python爬虫基础之百度翻译的实现
- leetcode 349. Intersection of Two Arrays
- Java自增原子性问题(测试Volatile、AtomicInteger)
- 判断app一个APP页面是原生的还是H5页面
- pat说反话(java)
- Ubuntu 14.04 下读取CPU温度
- Carthage管理依赖库
- 详解spring 每个jar的作用
- android 跳转到手机内存中查找文件,并上传音频文件
- 获取android软键盘高度