AC Python Solution 208ms


  • 1
    H
    class Solution:
        # @param {integer[]} nums
        # @return {integer[][]}
        def threeSum(self, nums):
            result = []
            if len(nums) < 3:
                return result
            num = sorted(nums)
            for i in range(len(num)-2):
                # avoid duplicates
                if i == 0 or num[i] > num[i-1]:
                    negate = - num[i]
                    start = i + 1
                    end = len(num) - 1
                    
                    while start < end:
                        # sum == 0
                        if num[start] + num[end] == negate:
                            result.append([num[i], num[start], num[end]])
                            start += 1
                            end -= 1
                            # avoid duplicates
                            while start < end and num[end] == num[end+1]:
                                end -= 1
                            while start < end and num[start] == num[start-1]:
                                start += 1
                        # sum < 0
                        elif num[start] + num[end] < negate:
                            start += 1
                        # sum > 0
                        else:
                            end -= 1
            return result

Log in to reply
 

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