双指针算法

2019-10-31  本文已影响0人  Hmcf

元素:数组
目标:求三数之和
思路:数组遍历

上代码:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        lenums = len(nums)
        for i in range(lenums-2):
            if i==0 and nums[i]>0:
                break
            if i>0 and nums[i]==nums[i-1]:
                continue
            left = i+1
            right = lenums - 1
            while left < right:
                sums = nums[i]+nums[left]+nums[right]
                if sums < 0:
                    left += 1
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
                elif sums > 0:
                    right -= 1
                    while left < right and nums[right] == nums[right + 1]:
                        right -= 1
                else:
                    res.append([nums[i],nums[left],nums[right]])
                    left +=1
                    right -=1
                    while left < right and nums[left]==nums[left-1]:
                        left +=1
                    while left < right and nums[right]==nums[right+1]:
                        right -=1
        return res
1572512598(1).png
上一篇下一篇

猜你喜欢

热点阅读