leedcode-两个数组的交集

自己写的:

from typing import List  # 导入List类型,用于函数参数和返回类型的注解

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # 初始化一个空列表,用于存储两个列表的交集
        mylist = []

        # 遍历nums1中的每个元素
        for i in nums1:
            # 检查当前元素是否也存在于nums2中
            if i in nums2:
                # 如果存在,则将当前元素添加到mylist中
                mylist.append(i)
        
        # 使用集合去除mylist中的重复元素,并转换回列表
        res = list(set(mylist))
        
        # 返回交集列表
        return res

哈希表实现:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:

        # 有一个数组为空,则交集为空
        if not nums1 or not nums2:
            return []

        # 初始化哈希表
        hash = {}
        # 初始化结果列表,存放最后结果
        res = []

        # 哈希表 key 为 nums1 数组中的数,value 为值
        for i in nums1:
            if not hash.get(i):
                hash[i] = 1
        # 遍历 nums,如果 nums2 数组中的数出现在哈希表中,对应数放入结果列表,对应 value 值置-为0
        for j in nums2:
            if hash.get(j):
                res.append(j)
                hash[j] = 0

        return res

 

posted @ 2024-04-11 14:28  Junior_bond  阅读(10)  评论(0)    收藏  举报