[leetcode] 15. The sum of three numbers (python+ converted to the sum of two numbers + deduplication)

insert image description here
insert image description here

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # 思路:转为两数之和
        # for循环遍历先固定一个数字a,寻找另外两个数字之和=-a(双指针)
        # 难点:去重{1. 排序; 2.加规则约束}
        nums = sorted(nums)
        res = []
        for i in range(len(nums)):
            if nums[i] > 0: # 剪枝,nums[i]若为正数,后边的也都是正数,没有匹配的了。
                return res
            if i > 0 and nums[i] == nums[i-1]: # 写 nums[i] == nums[i+1],会越界
                continue
            tar = 0 - nums[i]
            left, right = i + 1, len(nums) - 1
            while left < right:
                summ = nums[left] + nums[right]
                if summ == tar:
                    res.append([nums[i], nums[left], nums[right]])
                    while left < right and nums[left] == nums[left+1]:
                        left += 1
                    while left < right and nums[right] == nums[right-1]:
                        right -= 1
                    left += 1
                    right -= 1
                elif summ < tar:
                    left += 1
                else:
                    right -= 1
        return res

おすすめ

転載: blog.csdn.net/xiaoyue_/article/details/131608279