leetcode: explore-array-26 列表取交集 II

时间:2022-07-23
本文章向大家介绍leetcode: explore-array-26 列表取交集 II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

leetcode explore 初级算法第六题。原题链接:

https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/26/

题目分析

因为题目不是很长,这里把题目贴出来:

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?

题目意思,敲重点: 1、找出两个列表里重复的元素 2、不仅仅是取交集这么简单,注意 Note 里的那句话:

Each element in the result should appear as many times as it shows in both arrays.

即交集的定义是只要元素出现,但结果里需要展示出现次数最少的。比如 nums1 = [1,2,2,1], nums2 = [2,2] 按题意取交集,如果正常按数学思维取交集结果应该是 [2],但题目意思是次数也要算在内,所以答案是 [2, 2]。

因此,整个题目应该是数字 + 出现次数一起取交集。答案不限制数字顺序。

参考答案

因为题目并没有对空间条件有什么限制,所以我们可以引入中间的一些 list 或者 dict 来存储中间结果。很容易想到用 dict,key 为数字,值为出现次数,然后如果两个 dict 里均有此数字,则取最小的次数做为当前数字的交集结果。

参考代码如下:

from collections import defaultdict


class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        # 转为字典,key 为数字,value 为次数
        d1 = defaultdict(int)
        for n in nums1:
            d1[n] += 1

        d2 = defaultdict(int)
        for n in nums2:
            d2[n] += 1

        result = []
        for n, v in d1.items():
            result.extend([n] * min(v, d2[n]))
        return result

这里有一个小的知识点,也算是代码比较优雅的写法,即用到了 defaultdict。它的用法很简单,通常我们在申明一个普通的 dict 时,如果 key 不存在,通过 dict[key] 的形式会报错,只能通过 dict.get(key) 的返回是否为 None 来判断是否存在 key (或者通过 in)。即:

d1 = defaultdict(int)
for n in nums1:
    d1[n] += 1

# 等价于:
d1 = {}
for n in nums1:
    if d1.get(n):
        d1[n] += 1
    else:
        d1[n] = 1