#349. 两个数组的交集

#349. 两个数组的交集

题目

给定两个数组,求两个数组的交集。注意交集里每一个元素必须是唯一的。

解答

集合解法

  • 把两个数组转化成set,去除重复元素
  • 循环更短的set,把其中出现在第二个set里的元素记录在数组中。
class Solution:
    def set_intersection(self, set1: Set[int], set2: Set[int]) -> List[int]:
        return [x for x in set1 if x in set2]
        
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        #if set1 is shorter, iterate over set1 to see presence in set2
        if len(set1) < len(set2):
            return self.set_intersection(set1, set2)
        else:
            return self.set_intersection(set2, set1)

集合交集解法

将两个数组转化成集合,直接用内置函数返回交集。

def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
    set1 = set(nums1)
    set2 = set(nums2)
    return list(set1 & set2)

收获

  • set的属性:无序,无重复元素

  • 形成数组 – 代码段的运行结构构成了数组

    • [f(x) if condition else g(x) for x in sequence]
      
    • [f(x) for x in sequence if condition]
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值