Loading

leetcode15 三数之和

思路:

首先排序

依次遍历列表中的每个数 i

针对这个数找它之后的列表中的两个数组合,计算三数之和是否为0。

用双指针来指定后面两个数的组和,左指针为i+1,右指针为lenth-1.

如果当前三数之和大于零,则右指针左移;反之,左指针右移

如果三数之和等于零,记录这三个数的组合。同时右指针左移,左指针右移,为了找基于 i的第二对组合

如果 i 的下一个数和他相等,则跳过。因为在刚才的循环里,已经找到基于 i 的所有组合了。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        ans = []
        lenth = len(nums)
        
        if not nums or lenth <= 2:
            return ans
        nums.sort()
        for i in range(lenth):
            num1 = nums[i]
            if num1 > 0:
                return ans
            if i > 0 and num1 == nums[i-1]:
                continue
            left = i + 1
            right = lenth - 1

            while left < right:
                sum_ = num1 + nums[left] + nums[right]
                if sum_ < 0:
                    left += 1
                elif sum_ > 0:
                    right -= 1
                else:
                    ans.append([num1, 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
        return ans

 

posted @ 2021-08-18 11:11  climber_dzw  阅读(33)  评论(0编辑  收藏  举报