LeetCode 349. Intersection of Two Arrays && 350. Intersection of Two Arrays II
来源:互联网 发布:合肥seo 编辑:程序博客网 时间:2024/05/17 22:49
描述
两道题目都是求交集,前者要求最后的结果集中只存在一个相同的值,后者要求尽结果集中应该有尽可能多的相同值(以共同值较少的数量为准)。
解决
349直接暴力遍历的,复杂度为O(n^2)。
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> ans; map<int, int> m; auto nums1_end = nums1.end(); auto nums2_end = nums2.end(); for (auto it = nums1.begin(); it != nums1_end; ++it){ if (m[*it] == 0){ for (auto zz = nums2.begin(); zz != nums2_end; ++zz){ if (*zz == *it && m[*it] == 0){ ans.push_back(*it); m[*it] = 1; } } } } return ans; }};
350就是两个集合同时向前遍历,复杂度为O(n)。
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> res; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto it1 = nums1.begin(); auto it2 = nums2.begin(); while (it1 != nums1.end() && it2 != nums2.end()){ while (it1 != nums1.end() && it2 != nums2.end() && *it1 == *it2){ res.push_back(*it1); it1++, it2++; } while (it1 != nums1.end() && it2 != nums2.end() && *it1 < *it2){ it1++; } while (it1 != nums1.end() && it2 != nums2.end() && *it1 > *it2){ it2++; } } return res; }};
0 0
- 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
- [leetcode]350. Intersection of Two Arrays II
- String的compareTo方法底层代码
- RT-thread内核之定时器管理
- 判断是否微信打开实现跳转
- mac os 安装git 教程
- 浅析java反射
- LeetCode 349. Intersection of Two Arrays && 350. Intersection of Two Arrays II
- linq
- 三种增长模式
- URL中编码URL特殊字符
- Python Socket 编程,OSError: [Errno 98] Address already in use
- RT-thread内核之系统时钟
- iOS webview 加载html 乱码 需要UTF8转码
- Hive 或 Impala 的数据类型与 对应底层的 Parquet schema的数据类型不兼容
- linux 常用命令