[LeetCode] 15. 3Sum
2021. 1. 10. 20:54ㆍProblem Solving/LeetCode
https://leetcode.com/problems/3sum/
내 풀이
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
triplets = []
nums.sort()
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:
sum = nums[i] + nums[left] + nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else: # sum은 0
triplets.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 triplets
투포인터를 이용해 풀었다.
책 정보
|
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] 238. Product of Array Except Self (0) | 2021.01.10 |
---|---|
[LeetCode] 561. Array Partition I (0) | 2021.01.10 |
[LeetCode] 1. Two Sum (1) | 2021.01.07 |
[LeetCode] 5. Longest Palindromic Substring (0) | 2021.01.07 |
[LeetCode] 49. Group Anagrams (0) | 2021.01.06 |