python-leetcode-三数之和

15. 三数之和 - 力扣(LeetCode)

python 复制代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()  # 排序
        n = len(nums)
        res = []

        for i in range(n):
            # 剪枝:如果当前数 > 0,三数之和不可能为 0
            if nums[i] > 0:
                break

            # 去重:跳过重复元素
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            # 双指针
            left, right = i + 1, n - 1

            while left < right:
                total = nums[i] + nums[left] + nums[right]

                if total == 0:
                    res.append([nums[i], nums[left], nums[right]])

                    # 去重:跳过相同的 left 和 right
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1

                    left += 1
                    right -= 1

                elif total < 0:
                    left += 1  # 和偏小,左指针右移
                else:
                    right -= 1  # 和偏大,右指针左移

        return res   
相关推荐
We་ct11 分钟前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
weixin_3954489117 分钟前
main.c_0222cursor
c语言·前端·算法
Zik----39 分钟前
Leetcode27 —— 移除元素(双指针)
数据结构·算法
踩坑记录1 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
陆嵩1 小时前
GMRES 方法的数学推导及其算法表示
算法·概率论·arnoldi·gmres·minres·givens·hessenberg
天真小巫1 小时前
2026.2.21总结
职场和发展
plus4s1 小时前
2月22日(94-96题)
算法
学历真的很重要1 小时前
【系统架构师】第三章 数据库系统知识 - 数据库基础到关系代数(详细版)
数据库·学习·职场和发展·系统架构·系统架构师
tankeven2 小时前
HJ98 喜欢切数组的红
c++·算法
adore.9682 小时前
2.22 oj基础92 93 94+U12
数据结构·c++·算法