1. 程式人生 > >Python實現"兩個陣列的交集||"的兩種方法

Python實現"兩個陣列的交集||"的兩種方法

給定兩個陣列,寫一個方法輸出它們的交集

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]

注意:

輸出結果中每一個元素出現的次數和兩個陣列中 該元素同時出現的次數的一致

輸出結果元素順序不做要求

進階:

如果給定的陣列已經按序排好,如何調整優化你的演算法?

如果nums1的長度小於nums2,哪一種演算法更好?

如果nums2的元素儲存在磁碟上,磁碟記憶體有限以致於無法一次性載入所有元素,此時該怎麼辦?

1:不考慮進階。排序nums1和nums2,然後進行相應操作

def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        numsList = []
        count1 = 0
        count2 = 0
        while count1 < len(nums1) and count2 < len(nums2):
            if nums1[count1] == nums2[count2]:
                numsList.append(nums1[count1])
                count1 += 1
                count2 += 1
            elif nums1[count1] < nums2[count2]:
                count1 += 1
            else:
                count2 += 1
        return numsList

2:(不考慮元素排序)藉助字典,存放nums1中出現的元素和對應的次數,然後訪問nums2,進行對應操作(參考他人)

def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1Dic = {}
        numsList = []
        for i in nums1:
            if nums1Dic.get(i):
                nums1Dic[i] += 1
            else:
                nums1Dic[i] = 1
        for i in nums2:
            if nums1Dic.get(i) > 0:
                numsList.append(i)
                nums1Dic[i] -= 1
        return numsList