天天看點

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]

]

python代碼

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        ans = []
        nums.sort()
        n = len(nums)
        for i in range(n):
            if nums[i]>0:
                return ans
            if (i>0 and nums[i]==nums[i-1]):
                continue
            L = i + 1
            R = n - 1
            while(L<R):
                if nums[i]+nums[L]+nums[R]==0:
                    sub_ans = [nums[i], nums[L], nums[R]]
                    sub_ans.sort()
                    ans.append(sub_ans)
                    while(L<R and nums[L]==nums[L+1]):
                        L += 1
                    while(L<R and nums[R]==nums[R-1]):
                        R -= 1
                    L +=1
                    R -=1
                elif nums[i]+nums[L]+nums[R]>0:
                    R -= 1
                else:
                    L += 1
        return ans