[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]

]

代码:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        solution = []
        if not nums:
            return solution

        #对数组先排序            
        sortNum = sorted(nums)

        for i in range(len(sortNum)):
            if i != 0 and sortNum[i] == sortNum[i - 1]:
                continue
            c = - sortNum[i]
            a, b = i + 1, len(sortNum) - 1
            #双指针
            while a < b :
                if sortNum[a] + sortNum[b] == c:
                    res.append([sortNum[i], sortNum[a], sortNum[b]])
                    a += 1
                    b -= 1
                    while a < b and sortNum[a] == sortNum[a - 1]:
                        a += 1
                    while a < b and sortNum[b] == sortNum[b + 1]:
                        b -= 1
                elif sortNum[a] + sortNum[b] > c:
                    b -= 1
                else:
                    a += 1
                    
        return solution

猜你喜欢

转载自www.cnblogs.com/statlearning2019/p/10345167.html
今日推荐