5/09/2020

[LeetCode] 15. 3Sum

Problem : https://leetcode.com/problems/3sum/

Sort the input number array first. Then iterate the number array to pick up the number 'a'.  After that use 2 pointers algorithm to locate the number 'b' and 'c' which meet the equation  b + c = 0 - a

Time Complexity :   O ( len(nums) * len(nums) /  2) 
Space Complexity:   O ( len(nums) ) 

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        # sort input numbers
        nums.sort()
        
        L = len(nums)
        result = []
        
        for i in range(L - 2):
            # skip duplicate number 'a'
            if i > 0 and nums[i] == nums[i-1]:
                continue
            
            target = 0 - nums[i]
            
            left, right = i + 1, L - 1
            
            while left < right:
                if nums[left] + nums[right] == target:
                    result.append([nums[i], nums[left], nums[right]])
                    
                    # skip duplicate number 'b'
                    j = left + 1
                    while j < right and nums[j] == nums[left]:
                        j += 1
                    
                    left = j
                    
                    # skip duplicate number 'c'
                    k = right - 1
                    while  k > left and nums[k] == nums[right]:
                        k -= 1
                        
                    right = k
                    
                    # continue to search next combination
                    continue
                    
                if nums[left] + nums[right] < target:
                    left += 1
                else:
                    right -= 1
        
        return result

No comments:

Post a Comment