(Medium #15) 3Sum

Problem

Given an array nums of n integers, are there elements abc 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]
]

My solution (from other people)

class Solution:
    def threeSum(self, nums):
        result = []
        num_set = nums
        num_set.sort()

        for i in range(len(num_set)):
            choice_1 = num_set[i]
            if choice_1 > 0:
                break
            if (i>0 and choice_1 == num_set[i-1]):
                continue
            start = i+1
            end = len(num_set)-1

            while start < end:
                choice_2 = num_set[start]
                choice_3 = num_set[end]
                if choice_1+choice_2+choice_3 > 0:
                    end -= 1
                elif choice_1+choice_2+choice_3 < 0:
                    start += 1
                else: # choice_1+choice_2+choice_3 == 0:
                    while start<end and num_set[start] == num_set[start+1]:
                        start += 1
                    while start<end and num_set[end] == num_set[end-1]:
                        end -= 1
                    start += 1
                    result.append([choice_1, choice_2, choice_3])

        return result
Runtime: 764ms, Memory: 17.1MB
   

댓글