Skip to content

Latest commit

 

History

History
executable file
·
60 lines (49 loc) · 1.49 KB

015--3Sum.md

File metadata and controls

executable file
·
60 lines (49 loc) · 1.49 KB
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        res = []
        nums = sorted(nums)
        nums_length = len(nums)

        for i in range(nums_length-2):

            if i>0 and nums[i-1]==nums[i]:
                continue
            a = nums[i]
            low = i + 1
            high = nums_length - 1
            while (low < high):
                b = nums[low]
                c = nums[high]
                if a+b+c==0:
                    res.append([a,b,c])
                    while(low<nums_length-1 and nums[low]==nums[low+1]):
                        low += 1
                    while(high>0 and nums[high]==nums[high-1]):
                        high -= 1
                    low += 1
                    high -= 1
                elif (a+b+c)>0:
                    while(high>0 and nums[high]==nums[high-1]):
                        high -= 1
                    high -= 1
                else:
                    while(low<nums_length-1 and nums[low]==nums[low+1]):
                        low += 1
                    low += 1
        return res