leetcode_15. 三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

 

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        ans=[]
        n=len(nums)
        i=j=p=0
        for i in range(n):
            if i>0 and nums[i]==nums[i-1]:
                continue
            p=n-1
            for j in range(i+1,n):
                if j>i+1 and nums[j]==nums[j-1]:
                    continue
                         
                while p>j and nums[i]+nums[j]+nums[p]>0:
                    p-=1
                if p==j:
                    
                    break
                if nums[i]+nums[j]+nums[p]==0:
                    ans.append([nums[i],nums[j],nums[p]])
        return ans
原文地址:https://www.cnblogs.com/hqzxwm/p/14107753.html