LeetCode350. Intersection of Two Arrays II
来源:互联网 发布:网贷数据公司怎么样 编辑:程序博客网 时间:2024/06/18 17:42
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
寻找两个数组的交叉元素,可以重复。
可以重复的话,就直接考虑vector,直接在数组1里面找数组2的元素,如果存在,那么删除数组1里面的这个元素,并且把数组2当前的元素,插入vector中。最后返回vector。其实时间复杂度是O(n*n)。
解法一
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> res; vector<int>::iterator it1,it2; it2 = nums2.begin(); while (it2 != nums2.end()) { it1 = find(nums1.begin(),nums1.end(),*it2); if (it1 != nums1.end()) { nums1.erase(it1); res.push_back(*it2); } it2++; } return res; }};
解法二
先对两个数组进行排序,然后两个指针分别指向数组的起始位置,如果相等,则指针都指向下一个 位置;哪个指针指向的元素小,哪个指针就向下移动一位。
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()); vector<int>::iterator it1,it2; it1 = nums1.begin(); it2 = nums2.begin(); while( (it1!=nums1.end()) && (it2!=nums2.end())) { if (*it1 == *it2) { res.push_back(*it1); it1++; it2++; } else if (*it1 < *it2) it1++; else it2++; } return res; }};
0 0
- Leetcode350. Intersection of Two Arrays II
- Leetcode350. Intersection of Two Arrays II
- LeetCode350. Intersection of Two Arrays II
- leetcode350~Intersection of Two Arrays II
- leetcode350. Intersection of Two Arrays II
- Leetcode350 - Intersection of Two Arrays II(two pointers)
- Leetcode350. Intersection of Two Arrays II很简单的做法
- Leetcode350 Intersection of Two Arrays II &Leetcode Intersection of Two Arrays
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- sap常用符号
- php csv数据操作
- Bot主要技术流派
- MySQL根据表1字段更新表2字段
- 汇编语言 8086/8088指令系统
- LeetCode350. Intersection of Two Arrays II
- 命令各自用法 1/2
- 网易云音乐外链播放器测试
- PDO中包含三个预定义的类,它们分别是PDO、PDOStatement和PDOException
- python自动化之路-day9
- Android Studio--不能运行程序
- javascript小知识点
- APP自动化测试框架
- Grid Development Tools