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)
'LeetCode > Problems' 카테고리의 다른 글
Leet Code 83. Remove Duplicates from Sorted List [Easy] (1) | 2020.09.08 |
---|---|
LeetCode 561. Array Partition I [Easy] (0) | 2020.08.26 |
LeetCode 42. Trapping Rain Water [Hard] (1) | 2020.08.24 |
LeetCode 49. Group Anagrams (0) | 2020.08.19 |
LeetCode 819. Most Common Word (0) | 2020.08.18 |
댓글