본문 바로가기
LeetCode/Problems

LeetCode 15. 3Sum [Medium]

by 벤진[Benzene] 2020. 8. 25.

Problem:

Given an array nums of n integers, are there elements a, b, c 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:

Summary:

Using a two-pointer move left and the right pointer to compare the sum of three-element.

 

Code:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums.sort() #sort array to use two-pointer
        
        for i in range(len(nums)-2):
            
            if i>0 and nums[i] == nums[i-1]:
                continue
                
            left, right = i+1, len(nums)-1
                
            while left < right:
                three_sum = nums[i] + nums[left] + nums[right]
                
                if three_sum < 0:
                    left += 1
                elif three_sum > 0:
                    right -= 1
                else:
                    res.append([nums[i], nums[left], nums[right]])
                    
                    while left < right and nums[left] == nums[left+1]:
                        left += 1
                    while left < right and nums[right] == nums[right-1]:
                        right -= 1
                    
                    left += 1
                    right -= 1
        
        return res

Runtime:

O(N^2)

댓글