1. 程式人生 > >350. Intersection of Two Arrays II(python+cpp)

350. Intersection of Two Arrays II(python+cpp)

Given two arrays, write a function to compute their intersection. Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2] 
Output: [2,2] 

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 
Output: [4,9] 

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?

解釋: I直接set()再求交集就好了,但是這道題還要給出每個元素的個數,所以不能直接求交集 python程式碼:

from collections import Counter
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result=[]
        count1=
Counter(nums1) count2=Counter(nums2) for m in list((set(nums1)&set(nums2))): result+=[m]*min(count1[m],count2[m]) return result

c++程式碼:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<
int,int>map1,map2; vector<int> result; for (auto num:nums1) map1[num]++; for(auto num:nums2) map2[num]++; set<int>set1(nums1.begin(),nums1.end()); for (auto num :set1) { int _len=0; if(map2.count(num)) { _len=min(map1[num],map2[num]); for(int i=0;i<_len;i++) result.push_back(num); } } return result; } };

也可以不需要nums1和nums2都做統計,只統計nums1,在遍歷nums2的時候更新result,這樣速度更快。 c++程式碼(思想是一樣的,就不寫python程式碼了):

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<int,int>map1,map2;
        vector<int> result;
        for (auto num:nums1)
            map1[num]++;
        for (auto num:nums2)
        {
            if (map1[num]>0)
            {
                result.push_back(num);
                map1[num]--;
            }
        }
        return result;
    }
};

總結: 第二種方法,先用字典統計一個數組中每個元素出現的次數,在遍歷另一個數組的時候,更新result和字典中元素出現的次數-1,這樣不需要求set()也不需要求min(),因為最終結果的順序可以是任意的,所以可以這麼搞。這種方法更快,很棒~~!