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   
相关推荐
我爱C编程1 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7891 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
chao_7892 小时前
Selenium 自动化实战技巧【selenium】
自动化测试·selenium·算法·自动化
YuTaoShao2 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
怀旧,2 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
泛舟起晶浪2 小时前
相对成功与相对失败--dp
算法·动态规划·图论
地平线开发者2 小时前
地平线走进武汉理工,共建智能驾驶繁荣生态
算法·自动驾驶
IRevers3 小时前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶
前端拿破轮3 小时前
翻转字符串里的单词,难点不是翻转,而是正则表达式?💩💩💩
算法·leetcode·面试
凤年徐3 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题