leetcode15. 三数之和

☆樱花仙子☆ 提交于 2019-12-28 11:03:50

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[ [-1, 0, 1], [-1, -1, 2] ]

思路:

  1. 对数组进行排序,利用有序数组的性质设置三指针。i为当前指针,low=i+1high=len(nums)-1
  2. 三指针元素和相加为ans=nums[i]+nums[low]+nums[high]
  • 这时候若ans=0,则三指针符合题意,将其加入结果列表。但题目要求不能取重复值,有序列表中,重复元素是连续的,因此循环执行low=low+1,high=high-1, 直到两指针相遇或出现不同的元素。
  • ans>0,此时说明high偏大,根据 滑动窗口的思想,high指针左移。
  • 同理若ans<0,low指针右移。
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        l=[]
        for i in range(0,len(nums)):
            if nums[i]>0:
                break
            low=i+1
            high=len(nums)-1
            # 消除重复
            if i>0  and nums[i]==nums[i-1] :
                continue
            while low<high:
                ans=nums[i]+nums[low]+nums[high]
                if(ans==0):
                    l.append([nums[i],nums[low],nums[high]])
                    while (low<high and nums[low]==nums[low+1]):
                        low+=1
                    while (low<high and nums[high]==nums[high-1]):
                        high-=1
                    low+=1
                    high-=1
                    
                elif ans>0:
                    high=high-1
                elif ans<0:
                    low+=1
        return l
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!