Python Easy to understand solution


  • 0
    P

    def threeSum(self, nums):

        n = len(nums)
        if n < 3:
            return []
        
        nums.sort()
        first = 0
        res = []
        
        while nums[first] <= 0 and first < n - 2:
            
            target = 0 - nums[first]
            l = first + 1
            r = n - 1
            
            # two sum operation
            # in this specific one pass
            while l < r:
                if nums[l] + nums[r] == target:
                    res.append([-target, nums[l], nums[r]])
                    l += 1
                    r -= 1
                    
                elif nums[l] + nums[r] < target:
                    l += 1
                else:
                    r -= 1
                while l < r and l > first + 1 and nums[l] == nums[l-1]:
                    l += 1
                while l < r and r < n - 1 and nums[r] == nums[r+1]:
                    r -= 1
                    
            # move on to next first element for another two sum iteration
            first += 1
            while first < n - 2 and nums[first] <= 0 and nums[first] == nums[first-1]:
                first += 1
                
        return res

Log in to reply
 

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