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
相关推荐
shirsl15 分钟前
算法 Day 2 滑动窗口 + 栈 / 单调栈
开发语言·python·算法
土司大王1 小时前
LeetCode hot100 回溯专题总结:Java 通用模板、决策树模型
java·算法·leetcode·决策树
2601_962218611 小时前
万象生鲜系统订单全生命周期状态同步技术实现业务可视
大数据·数据库·人工智能·python·算法
那年窗外下的雪.2 小时前
AIDC 学习日志|第 22 天|All-Active/Single-Active 故障演练设计
服务器·网络·学习·算法·哈希算法
wzdark3 小时前
基于启发式搜索的最优路径规划算法研究4
算法
l1t3 小时前
用superpi、tinypi、tpi等工具计算圆周率的比较
c语言·算法
a187927218313 小时前
【算法】链表(二):链表上的双指针——变速、异链与定距,和一份路程账本
数据结构·算法·leetcode·链表·go·指针·环形链表
2601_958352904 小时前
还要写 AEC 算法?0 代码 + 6 个引脚,F-18 让通话清晰度提升 300%
人工智能·算法·降噪消回音
happyprince4 小时前
03-regmix-深刻观-哲学与升华
算法
一路向阳~负责的男人4 小时前
运动控制算法收录
算法