Intersection of Two Arrays II 两数

2021-03-17  本文已影响0人  nsnhejian

问题:

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.

给出两个数组,写一个函数得出他们的交。
示例:
  nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回[2, 2]
备注:
  返回值中的每个元素的次数应该和它在每个数组中出现的次数一样多都不一样。
  结果可以是任意顺序。

代码:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size();
        vector<int> nums3 = nums2;
        vector<int> res;
        for (int i = 0; i < len1; i++) {//令数组3等于数组2,每找到一个相同的元素,插入res中,再从nums3中删除,这样就可以找出全部相同的元素
            int len2 = nums3.size();
            for (int k = 0; k < len2; k++) {
                if (nums1[i] == nums3[k]) {
                    res.push_back(nums1[i]);
                    nums3.erase(nums3.begin()+k);
                    break;
                }
            }
        }
        return res;
    }
};

备注:

nums.erase(nums.begin()+k) 用于删除vector nums中的索引为k的元素

上一篇 下一篇

猜你喜欢

热点阅读