LeetCode-Hash-349. Intersection of Two Arrays && 350. Intersection of Two Arrays II
来源:互联网 发布:做淘宝代销店铺没人买 编辑:程序博客网 时间:2024/06/05 11:38
问题349:https://leetcode.com/problems/intersection-of-two-arrays/
Given two arrays, write a function to compute their intersection.
问题350:https://leetcode.com/problems/intersection-of-two-arrays-ii/
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
分析:先将两个数组从小到大排序。再用i和j分别代表两个数组的索引。遍历,如果nums1[i]nums2[j],则j加1.如果两者相等,就把这个值加到结果中。当然还有一些条件的限制。排除结果数组中重复出现的元素。
代码349:
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { std::sort(nums1.begin(),nums1.end()); std::sort(nums2.begin(),nums2.end()); int i=0; int j=0; int n1=nums1.size(); int n2=nums2.size(); vector<int> result; while(i<n1 && j<n2){ if(nums1[i]<nums2[j]) i++; else if(nums1[i]>nums2[j]) j++; else{ if(!result.size() || result.back()!=nums1[i]) result.push_back(nums1[i]); i++; j++; } } return result; }};
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { std::sort(nums1.begin(),nums1.end()); std::sort(nums2.begin(),nums2.end()); int n1=nums1.size(); int n2=nums2.size(); int i=0; int j=0; vector<int> result; while(i<n1 && j<n2){ if(nums1[i]<nums2[j]) i++; else if(nums1[i]>nums2[j]) j++; else{ result.push_back(nums1[i]); i++; j++; } } return result; }};
0 0
- LeetCode-Hash-349. Intersection of Two Arrays && 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- [Leetcode] 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode - 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- leetcode-350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- Windows 上Mali仿真实践编译OpenGL ES 3.0 Programming Guide 例程环境配置
- ESC/POS 工具类
- 使用SqlSrv调用sqlserver的存储过程
- android SwipeRefreshLayout嵌套ViewPager 滑动冲突问题
- J2EE规范——JDBC
- LeetCode-Hash-349. Intersection of Two Arrays && 350. Intersection of Two Arrays II
- linux shell的一些简单介绍
- Java正则表达式 特殊字符转义
- ISA-95和IEC62264
- Runtime Swizzling 详解
- 高精度减法
- 英文金曲大赛
- table合并单元格colspan和rowspan
- 设计模式(三):Builder模式