LeetCode-350 Intersection of Two Arrays II

来源:互联网 发布:linux 统计大文件行数 编辑:程序博客网 时间:2024/05/16 10:38

https://leetcode.com/problems/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].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
http://blog.csdn.net/smile_e0/article/details/51675012

二者差别是此题不需要去重

1、调用set_intersection(12ms)

class Solution {

public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> num(500);
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        auto iter = set_intersection(nums1.begin(),nums1.end(),nums2.begin(),nums2.end(),num.begin());
        num.resize(iter-num.begin());
        return num;
    }

};

2、sort排序后,利用两个指针扫描(8ms)

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> num;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        int len1 = nums1.size(), len2 = nums2.size(), i = 0, j = 0;
        while(i < len1 && j < len2){
            if(nums1[i] == nums2[j]){
                num.push_back(nums1[i]);
                i++;
                j++;
                continue;
            }
            if(nums1[i] < nums2[j])
                i++;
            else
                j++;
        }
        return num;
    }
};


0 0
原创粉丝点击