1. 程式人生 > >leetcode-350-Intersection of Two Arrays II(求兩個數組的交集)

leetcode-350-Intersection of Two Arrays II(求兩個數組的交集)

CA 更新 lse write limited elements 表示 app 順序

題目描述:

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?

要完成的函數:

vector<int> intersect(vector<int>& nums1, vector<int>& nums2)

說明:

1、這道題給定兩個vector,要求返回兩個vector的交集,比如nums1=[1,2,2,1],nums2=[2,2],返回的交集是[2,2],其中有多少個相同的元素就返回多少個。返回的交集不講究順序。

2、這道題看完題意,熟悉leetcode的同學應該會馬上想到先排序,排序之後的兩個vector來比較,時間復雜度會下降很多。

如果不排序,那就是雙重循環的做法,O(n^2),時間復雜度太高了。

先排序再比較的做法,代碼如下:(附詳解)

    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) 
    {
        sort(nums1.begin(),nums1.end());//給nums1排序,升序
        sort(nums2.begin(),nums2.end());//給nums2排序,升序
        int s1=nums1.size(),s2=nums2.size(),i=0,j=0;//i表示nums1元素的位置,j表示nums2元素的位置
        vector<int>res;//存儲最後結果的vector
        while(i<s1&&j<s2)//兩個vector一旦有一個遍歷完了,那麽就結束比較
        {
            if(nums1[i]<nums2[j])
            {
                while(nums1[i]<nums2[j]&&i<s1)//一直找,直到nums1[i]>=nums2[j]
                    i++;
                if(i==s1)//如果i已經到了nums1的外面,那麽結束比較
                    break;
            }
            else if(nums1[i]>nums2[j])
            {
                while(nums1[i]>nums2[j]&&j<s2)//一直找,直到nums2[j]>=nums1[i]
                    j++;
                if(j==s2)//如果j已經到了nums2的外面,那麽結束比較
                    break;
            }
            if(nums1[i]==nums2[j])//如果剛好相等,那麽插入到res中,更新i和j的值
            {
                res.push_back(nums1[i]);
                i++;
                j++;
            }
        }
        return res;
    }

上述代碼實測7ms,beats 98.05% of cpp submissions。

leetcode-350-Intersection of Two Arrays II(求兩個數組的交集)