Build 3Sum based on 2Sum

  • 2
    class Solution:
        # @return a list of lists of length 3, [[val1,val2,val3]]
        # 10:16
        def __init__(self):
            self.result = []
        def threeSum(self, num):
            last = None
            for i in range(len(num)):
                if num[i] is last:
                last = num[i]
                sum = 0 - num[i]
                twoSumResult = self.findTwoSum(num[i+1:], sum, num[i])
            return sorted(self.result)
        def findTwoSum(self, num, target, root):
            valMap = {}
            last = None
            for n in num:
                if n in valMap and [root, valMap[n], n] not in self.result:
                    self.result.append([root, valMap[n], n])
                    valMap[target-n] = n

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.