leetcode 练习(15,355)

LeetCode 练习

题15:3SUM

要求求得一个list中任意三个数的组合,对这三个数的要求是加起来和为0
我的思路没什么创新,就是遍历找三个不同数的组合,然后相加判断是否等于0,最后对整个list排序,并剔除重复项,返回new。希望以后能找到更简便的方法。
代码如下:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        new = []
        l = len(nums)
        for i in range(l):
            for j in range(l):
                if i!=j and nums[i]+nums[j] !=0 :
                    add = nums[i]+nums[j]
                    for r in range(l):
                        if r != i and r !=j:
                            add1 =add+nums[r]
                            if add1 == 0:
                                res.append([nums[i],nums[j],
                                            nums[r]])
        for k in res:
            k.sort()
        new.append(res[0])
        for k in res:
            if k  not in new:
                new.append(k)
        return new
nums=[1,0,-1,1,2,-3]
s = Solution()
print(s.threeSum(nums))

运行结果如下:
这里写图片描述

题355:求两个集合的交集

这对于python编程来说相对比较容易,就是判断一个是否在另一个集合中是否出现,并且出现的次数是怎样的。
代码如下:

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res=[]
        for k in nums1:
            if k in res:
                continue
            for j in nums2:
                if j in res:
                    continue
                if j == k :
                    l1 = len([i for i in range(len(nums1))
                              if nums1[i] == j])
                    l2 = len([i for i in range(len(nums2))
                              if nums2[i] == j])
                    for n in range(min(l1,l2)): # 如果相同的数在两个集合中的数量一样,就返回这个数量的数值,若不一样,返回最小数量的值
                            res.append(j)
        return res

nums1 = [1,1,2,3,4]
nums2 = [1,1,2,3]
s=Solution()
print(s.intersect(nums1,nums2))

结果如下:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值