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
相关推荐
Navigator_Z36 分钟前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年1 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3331 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
Nil2082 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
神工坊2 小时前
技术分享︱SIMFORGE HSF® 网格加密与热点加速技术实践
算法·hpc·网格·cae·工程仿真·数值引擎·samr
Nil2082 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
CV@CV2 小时前
世界模型与智能体协同推理逻辑
人工智能·算法·边缘计算·量子计算·具身智能
jiayoushijie-泽宣2 小时前
SHIFT-PathFormer:专家轨迹蒸馏、连续安全优化与超大迷宫实验
算法
UIU1143 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法