350. Intersection of Two Arrays II。
来源:互联网 发布:js实现动态进度条 编辑:程序博客网 时间:2024/06/01 09:25
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
这个题与349的差不多,不过最后交集的元素如果有多个重复,那么需要保存多个。这个就不能采用set来计算了,因为我们需要计算某个元素共有多少个。例如上述的:nums1中[1,2,2,1]共有两个2,那么每次在另一个数组num2中找到对应的一个2,就需要在num1和num2分别去除一个2。所以我们需要记录当前数组的元素还有多少个。可以使用map结构将其中一个vector转换成map,数组的元素作为map的key,元素的个数作为map的value。然后遍历另一个vector,如果vector的元素在map对应的value不为0,则说明这个元素还有重复的,则加入最后的结果中。
#include <iostream>#include <vector>#include <unordered_map>#include <unordered_set>using namespace std;class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> result; unordered_map<int,int> temp; for(auto num : nums1) { temp[num]++; } for(auto num : nums2) { if(temp[num]-- > 0) result.push_back(num); } return result; }};int main() { Solution s; vector<int> v1 = {1,2,3,1}; vector<int> v2 = {1,1}; vector<int> res = s.intersect(v1,v2); for(int num : res) { cout << num << endl; }}
阅读全文
0 0
- 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II【E】
- 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
- 350. Intersection of Two Arrays II
- 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
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- Oracle 创建用户语句
- 对反向传播算法(Back-Propagation)的推导与一点理解
- springBoot项目集成dubbox
- JSP web.xml <jsp-config>标签使用详解
- Java学习笔记之线程(二):线程的常用方法
- 350. Intersection of Two Arrays II。
- malloc 分配内存为零的问题
- 序列化和反序列化
- 一文弄懂神经网络中的反向传播法——BackPropagation
- unity渲染优化的相关问题
- Tomcat如何配置环境变量
- 金山云H.265编码荣膺世界最强视频编码软件称号
- rocket mq——批次实例
- 又一版 A+B