simple Python first twoSum then threeSum O(n^2)


  • 0
    H

    class Solution(object):
    def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: set
    """
    st = set()
    stRet = set()
    for v in nums:
    sub = target - v
    if sub in st:
    stRet.add(sub)
    st.add(v)
    return stRet

    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        lsRet = []
        pre = 1
        for i in range(len(nums)):
            one = nums[i]
            if one > 0:
                break
            if one == pre:
                continue
            pre = one
            stTwo = self.twoSum(nums[i+1:], -one)
            for two in stTwo:
                lsRet += [[one,two,-one-two]]
        return lsRet

Log in to reply
 

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