leetcode刷题之349.两个数组的交集

leetcode刷题之349.两个数组的交集

  • 题目
    给定两个数组,编写一个函数来计算它们的交集。
  • 示例 :
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
  • 说明
    • 输出结果中的每个元素一定是唯一的。
    • 我们可以不考虑输出结果的顺序。
  • 代码1:
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        c =[]
        for i in range(len(nums1)):
            if nums1[i] in nums2:
                c.append(nums1[i])
        return list(set(c))
# 执行用时 : 68 ms, 在Intersection of Two Arrays的Python提交中击败了37.18% 的用户
# 内存消耗 : 11.8 MB, 在Intersection of Two Arrays的Python提交中击败了33.95% 的用户
  • 算法说明:
    先建立一个空的列表c,然后将判断nums1[ ]中的元素是否在nums2[ ]中,如果在,将此元素添加到c中,返回c即可!

  • 代码2:

class Solution(object):
    def intersection(self, nums1, nums2):
	"""
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1) & set(nums2))
# 执行用时 : 36 ms, 在Intersection of Two Arrays的Python提交中击败了98.61% 的用户
# 内存消耗 : 11.8 MB, 在Intersection of Two Arrays的Python提交中击败了32.72% 的用户
  • 算法说明:
    用set()函数分别将nums1[ ]和nums2[ ]中的重复元素去除掉,然后用《&》运算将重复的元素选出,返回。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

O_胡萝卜_O

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值