class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def threeSum(self, num): returnlists =  #let num be sorted, .... num.sort() lasta = None #let a = num[i], this solution is to find (b + c) = -a for i in range(len(num)): #use lasta to avoid redundant a if num[i] == lasta: continue #use lastc to avoid redundant c lastc = None lasta = num[i] #this is -a nega = 0 - num[i] #make a set to store the b, then to find c newSet = set() #use range(i,..) to avoid (a, b)/(b, a) redundancies. for j in range(i, len(num)): #skip self if j != i: #check if -a - c is in set theval = nega - num[j] #not in and no repeating, get (a, b, c). if theval in newSet and lastc != num[j]: thislist = [theval, num[i], num[j]] lastc = num[j] thislist.sort() returnlists.append(thislist) #put b in set else: newSet.add(num[j]) return returnlists
My Python solution (accept)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.