Leetcode 15.三数之和

解法:两处去重+二分法

python 复制代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        visited_numi = [] # 第一处去重
        for i in range(len(nums) - 2):
            if nums[i] not in visited_numi:
                visited_numi.append(nums[i])
                sortnums = nums[i+1: ]
                l, r = 0, len(sortnums) - 1
                while r > l:
                    if sortnums[l] + sortnums[r] == - nums[i]: 
                        res.append([nums[i], sortnums[l], sortnums[r]])
                        while l < r and sortnums[l + 1] == sortnums[l]: l += 1 # 第二处去重
                        while l < r and sortnums[r - 1] == sortnums[r]: r -= 1
                        l += 1
                        r -= 1
                    elif sortnums[l] + sortnums[r] > - nums[i]: r -= 1
                    else: l += 1
        return res
相关推荐
数模竞赛Paid answer13 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆13 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
想吃火锅100514 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil20815 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣16 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
qeen8719 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI19 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶20 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
民乐团扒谱机20 小时前
【微实验】倒谱算法(Cepstrum)深度解析:原理、数学推导与代码实现
人工智能·算法·语音识别
evans在进步20 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode