[LeetCode] 15.三数之和 @Python

本文深入探讨了经典的三数之和算法问题,通过详细解释和Python代码实现,展示了如何在给定整数数组中找到所有唯一三元组,使得它们的和为零。文章强调了排序和双指针技巧在解决此类问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

Note:

The solution set must not contain duplicate triplets.

Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

代码

class Solution:
    def threeSum(self, nums):
        res = []
        nums.sort()   # 首先做排序
        for i in range(len(nums)-2):
            if nums[i] > 0:   # 如果nums[i]大于0,则三数和total必定>0,结束循环
                break
            if i>0 and nums[i]==nums[i-1]:   # 如果有重复nums[i],进入下一个循环,避免重复
                continue
                
            left, right = i+1, len(nums)-1
            while left < right:
                total = nums[i] + nums[left] + nums[right]
                
                if total < 0:   # 若total<0,说明三数和小了,需要加数字,故left右移
                    left += 1
                elif total > 0:   # 若total>0,说明三数和大了,需要减数字,故right左移
                    right -= 1
                else:
                    res.append([nums[i], nums[left], nums[right]])
                    while left < right and nums[left] == nums[left+1]:  # 查看left后是否有重复数字,有则跳过
                        left += 1
                    while left < right and nums[right] == nums[right-1]:   # 查看right前是否有重复数字,有则跳过
                        right -= 1
                    left += 1
                    right -= 1
        
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值