Leetcode 15.三数之和

Leetcode 15.三数之和_第1张图片

解法:两处去重+二分法

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

你可能感兴趣的:(Python编程,基础算法与数据结构,leetcode,算法)