leetcode 15

leetcode 15

想法就是遍历每个元素,计算他和其他元素的和,列表中找出来和的相反数。但是提交时候超时。不知道什么原因,复杂度的话不是应该只有O(n^2)吗。而且在本地跑也挺快的啊。
311 / 313 个通过测试用例





class Solution:
    def threeSum(self,num ):


        def three(a, b):
            new = num[::]
            new.remove(a)
            new.remove(b)
            pro = -(a + b)

            if pro in new:
                return [1,[a, b, pro]]
            else:
                return [0]

        num.sort()
        c = []


        for i in range(len(num)):
            for j in range(i+1, len(num)):
                if num[i]>0 and num[j]>0:
                    return c
                if ([num[i],num[j],-(num[i]+num[j])] in c) or \
                ([num[j],num[i],-(num[i]+num[j])] in c) or \
                ([num[i],-(num[i]+num[j]),num[j]] in c) or \
                ([num[j],-(num[i]+num[j]),num[i]] in c) or \
                ([-(num[i]+num[j]),num[i],num[j]] in c) or \
                ([-(num[i]+num[j]),num[j],num[i]] in c):
                    continue
                h=three(num[i], num[j])
                if h[0]==1:
                    c.append(h[1])
        



        

        
        return  c

感觉题目的难点不在于解决,而在于怎么避免重复的计算。看了题解,知道了三指针的概念:
leetcode 15_第1张图片

你可能感兴趣的:(leetcode 15)