LeetCode350. Intersection of Two Arrays II 解题小结
Posted 医生工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode350. Intersection of Two Arrays II 解题小结相关的知识,希望对你有一定的参考价值。
题目:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
相比较I,这个题目允许答案出现重复的。想法就是做一个map统计nums1元素出现次数,然后nums2每次遍历都看看元素出现次数。
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> maps; vector<int> res; for (int i = 0; i < nums1.size(); ++i){ maps[nums1[i]]++; } for (int i = 0; i < nums2.size(); ++i){ if (maps.find(nums2[i]) != maps.end()){ if (maps[nums2[i]] != 0) { res.push_back(nums2[i]); maps[nums2[i]]--; } } } return res; } };
另一种方法就是讲两个数组排序,然后找到重叠的部分。
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { int idx1 = 0, idx2 = 0; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> num; while (idx1 < nums1.size() && idx2 < nums2.size()){ if (nums1[idx1] == nums2[idx2]){ num.push_back(nums1[idx1]); ++idx1; ++idx2; } else if (nums1[idx1] < nums2[idx2]) idx1++; else idx2++; } return num; } };
以上是关于LeetCode350. 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(LeetCode)