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
相关推荐
ZC跨境爬虫4 分钟前
LeetCode 13. 罗马数字转整数(多解法详解 + Java Python 实现)
java·python·leetcode
.道阻且长.9 分钟前
10.LeetCode算法习题讲解--滑动窗口--最大连续为一的个数
算法·leetcode·职场和发展
学习中.........44 分钟前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
城管不管1 小时前
重生——第十次面试之开源中国一面挂
java·linux·开发语言·算法·面试·职场和发展·开源
地平线开发者2 小时前
征程6|YOLOv5x 在 Horizon 征程6 上的端到端部署实践(下)
算法·自动驾驶
speop2 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
艾为电子2 小时前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
大熊背3 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_3 小时前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai3 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法