【leetcode】350. Intersection of Two Arrays II

来源:互联网 发布:生死狙击矩阵怎么得 编辑:程序博客网 时间:2024/05/22 10:48

一、题目描述

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.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?


题目解读:找出两个数组的交集


思路:使用map存储nums1中的整数和出现的次数,遍历nums2,通过查找map发现只要次数>0,就存储到结果向量中。最后返回结果向量。


c++代码:(16ms)

class Solution {public:    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        vector<int> result;        map<int, int> count;        int len1 = nums1.size();        int len2 = nums2.size();        for(int i=0; i<len1; i++){            count[nums1[i]] ++;        }        for(int i=0; i<len2; i++){            if(count[nums2[i]]-- > 0)                result.push_back(nums2[i]);        }        return result;    }};

nums1.size:m

nums2.size:n

时间复杂度O(m+n),空间复杂度O(m+n)


其他方法:sort

代码:

class Solution {public:    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        sort(nums1.begin(), nums1.end());        sort(nums2.begin(), nums2.end());        int n1 = (int)nums1.size(), n2 = (int)nums2.size();        int i1 = 0, i2 = 0;        vector<int> res;        while(i1 < n1 && i2 < n2){            if(nums1[i1] == nums2[i2]) {                res.push_back(nums1[i1]);                i1++;                i2++;            }            else if(nums1[i1] > nums2[i2]){                i2++;            }            else{                i1++;            }        }        return res;    }};


nums1.size:m

nums2.size:n

时间复杂度O(max(m,n) log(max(m, n)))  空间复杂度O(m + n)

0 0