3Sum

 

15. 3Sum

Solution

  1. Sort the array.

  2. Loop for the 1st num.

  3. Use two pointer to find the 2Sum.

Complexity: O(n * n)

def threeSum(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    res = []
    nums = sorted(nums)
    pre = None
    for i, num in enumerate(nums):
        if pre == num:
            continue
        res += self.twoSum(nums, i, -num)
        pre = num
    return res
    
def twoSum(self, nums, i, target):
    res = []
    start, end = i+1, len(nums) - 1
    while start < end:
        curr = nums[start] + nums[end]
        if curr == target:
            res.append([nums[i], nums[start], nums[end]])
            while start < end and nums[start] == nums[start + 1]:
                start += 1
            while start < end and nums[end] == nums[end - 1]:
                end -= 1
            start += 1
            end -= 1
        elif curr > target:
            end -= 1
        else:
            start += 1
    return res