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   
相关推荐
猫头虎8 分钟前
HAMi 2.7.0 发布:全面拓展异构芯片支持,优化GPU资源调度与智能管理
嵌入式硬件·算法·prompt·aigc·embedding·gpu算力·ai-native
漫漫不慢.11 分钟前
算法练习-二分查找
java·开发语言·算法
如竟没有火炬30 分钟前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
Greedy Alg33 分钟前
LeetCode 236. 二叉树的最近公共祖先
算法
爱吃生蚝的于勒1 小时前
【Linux】零基础学会Linux之权限
linux·运维·服务器·数据结构·git·算法·github
兮山与2 小时前
算法3.0
算法
爱编程的化学家2 小时前
代码随想录算法训练营第27天 -- 动态规划1 || 509.斐波那契数列 / 70.爬楼梯 / 746.使用最小花费爬楼梯
数据结构·c++·算法·leetcode·动态规划·代码随想录
CoovallyAIHub2 小时前
告别等待!十条高效PyTorch数据增强流水线,让你的GPU不再"饥饿"
深度学习·算法·计算机视觉
海琴烟Sunshine2 小时前
leetcode 66.加一 python
python·算法·leetcode