350. 两个数组的交集 II(python)

问题描述

350. 两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]

说明:

  • 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
  • 我们可以不考虑输出结果的顺序。

问题分析

  1. 直接的想法是:遍历数组1,查看是否含于数组2,如果是的话,删除数组2中的该元素,直至数组1循环完毕。接下来考虑是将长数组(n)还是短数组(m)作为数组1,结论是:遍历长数组,匹配短数组。理由如下:虽然两种情况的最坏最好时间复杂度都是 O ( m 2 ) O(m^2) O(m2) O ( n 2 ) O(n^2) O(n2),但是遍历长数组过程中,匹配短数组有这样一个条件:当短数组空时,打破循环,因此,相对而言遍历长数组时间复杂度更优。实验验证也是如此。
  2. 使用哈希表结构进一步优化时间复杂度。

实现代码

# 遍历匹配
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        if len(nums1) > len(nums2):
            res = self.find(nums1, nums2)
        else:
            res = self.find(nums2, nums1)
        
        return res

    def find(self, longnums, shortnums):
        res = []
        for i in range(len(longnums)):
            if shortnums==[]:
                break
            if longnums[i] in shortnums:
                res.append(longnums[i])
                shortnums.remove(longnums[i])

        return res
# 哈希表结构
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res_dict = {}
        res = []
        for i in nums1:
            if i in res_dict:
                res_dict[i] += 1
            else:
                res_dict[i] = 1
        for j in nums2:
            if j not in res_dict:
                continue
            else:
                if res_dict[j] == 0:
                    continue
                else:
                    res.append(j)
                    res_dict[j] -= 1
    
        return res

你可能感兴趣的:(Leecode)