3Sum - LeetCode

3Sum - LeetCode

题目:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

分析:

我们直接循环整个S,然后在每一个点处,有两个指针,一个指向S[i+1],一个指向S[n-1],开始从两头往中间查找,并把满足所有两指针加起来等于这个点的加入res。这里有一点说的,就是res如果一开始就是list的话,你还需要判断是否res里已经有了重复的,时间会增加;所以我们把res设为set,减短时间。因为set结点本身就已经是不可重复的。

代码:

class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        if not num or len(num)<3:
            return []
        num = sorted(num)
        res = set()
        for i in range(len(num)):
            l = i+1
            h = len(num)-1
            while l < h:
                if num[l] + num[h] > - num[i]:
                    h -= 1
                elif num[l] + num[h] < - num[i]:
                    l += 1
                else:
                    res.add((num[i],num[l],num[h]))
                    l += 1
        return [list(t) for t in res]


你可能感兴趣的:(3Sum - LeetCode)