Simple Solution by Python beats 96.71%


  • 0
    H
    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums.sort()
            ans = []
            length = len(nums)
            if length < 3: return ans
            i = 0
            while(i < length-2):
                if nums[i] > 0: break
                j = i+1; k = length-1
                while(j < k):
                    sum = nums[i] + nums[j] + nums[k]
                    if sum > 0:
                        k -= 1
                        while nums[k] == nums[k+1] and j < k:
                            k -= 1
                    elif sum < 0:
                        j += 1
                        while nums[j] == nums[j-1] and j < k:
                            j += 1
                    else:
                        ans.append([nums[i], nums[j], nums[k]])
                        k -= 1
                        j += 1
                        while nums[k] == nums[k+1] and j < k:
                            k -= 1
                        while nums[j] == nums[j-1] and j < k:
                            j += 1
                i += 1
                while nums[i] == nums[i-1] and i < length-2:
                    i += 1
            return ans
    

Log in to reply
 

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