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   
相关推荐
草莓火锅2 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望2 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng2 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88892 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
偷偷的卷3 小时前
【算法笔记 11】贪心策略六
笔记·算法
ZPC82103 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
_w_z_j_3 小时前
爱丽丝的人偶
算法
老前端的功夫4 小时前
Vue2中key的深度解析:Diff算法的性能优化之道
前端·javascript·vue.js·算法·性能优化
想要打 Acm 的小周同学呀4 小时前
爬虫相关的面试问题
爬虫·selenium·职场和发展
yongui478345 小时前
基于深度随机森林(Deep Forest)的分类算法实现
算法·随机森林·分类