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   
相关推荐
sin_hielo9 分钟前
leetcode 3510
数据结构·算法·leetcode
努力学算法的蒟蒻15 分钟前
day64(1.23)——leetcode面试经典150
面试·职场和发展
Anastasiozzzz19 分钟前
力扣hot100 20.有效的括号 解析
java·算法·面试·力扣
CrazyClaz25 分钟前
负载均衡算法
算法·负载均衡
嵌入式小能手34 分钟前
飞凌嵌入式ElfBoard-系统信息与资源之休眠
c语言·开发语言·算法
历程里程碑1 小时前
哈希3 : 最长连续序列
java·数据结构·c++·python·算法·leetcode·tornado
闻缺陷则喜何志丹1 小时前
【图论】P9661 [ICPC 2021 Macao R] Sandpile on Clique|普及+
c++·算法·图论·洛谷
2401_841495641 小时前
【LeetCode刷题】两两交换链表中的节点
数据结构·python·算法·leetcode·链表·指针·迭代法
傻啦嘿哟1 小时前
构建命令行单词记忆工具:JSON词库与复习算法的完美结合
算法·json
mjhcsp1 小时前
一种新的LCA算法
算法