首页 > 代码库 > 【LeetCode】350. Intersection of Two Arrays II 解题小结

【LeetCode】350. 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;    }};

 

【LeetCode】350. Intersection of Two Arrays II 解题小结