[LeetCode] 15. 3Sum

题目内容

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

https://leetcode-cn.com/problems/3sum/

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

 


题目思路

这道题目的要求在于找到3个和为0的数字组合。题目本身并不难,可以考虑先找到一个数字,然后简化成找到2个数字组合的问题。但是当给定的nums非常大时,效率会变得很低。所以可以对查找方式和输出进行优化。

要求3个数字的和为0,所以除非是全0,否则至少有1个负数。因而组合只可能有两种情况:[0,0,0]和[正数,负数,正/负数]

我们可以把数字分拣到正数数组和负数数组进行查找。在输出结果的时候,为了避免重复输出,我们可以要求k=-(i+j)的k是i,j中间的那个数时才添加到队尾。


程序代码

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        count={}
        res=[]
        for i in set(nums):
            count[i]=nums.count(i)
        
        if 0 in nums and count[0]>=3:
            res.append([0,0,0])
        
        positive=[i for i in count if i>0]
        negative=[i for i in count if i<0]
        
        for i in positive:
            for j in negative:
                k=-(i+j)#为了节约时间,我们可以规定K必须是在i,j中间的那个数时才插入。
                if k in count:
                    if j<k<i or ((k==i or k==j) and count[k]>=2):
                        res.append([j,k,i])
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值