Friday, September 19, 2014

Leetcode: 3Sum @Python

class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        A=sorted(num)
        n=len(A)
        rst=[]
        for k in range(n-2):
            a=A[k]
            if k>0 and a==A[k-1]:
                continue
            i=k+1
            j=n-1
            while j>i:
                s2=A[i]+A[j]
                if s2==-A[k]:
                    rst.append([A[k],A[i],A[j]])
                    while j>i:
                        i+=1
                        j-=1
                        if A[i]!=A[i-1] or A[j]!=A[j+1]:
                            break
                elif A[k]+s2>0:
                    while j>i:
                        j-=1
                        if A[j]!=A[j+1]:
                            break
                else:
                    while j>i:
                        i+=1
                        if A[i]!=A[i-1]:
                            break
        return rst

No comments :

Post a Comment