🤴Day 3 Array 3Sum(... Three...? 그거아니다)
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.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
투포인터 이용 풀이
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort() # 어차피 합을 구하는거니 정렬해버리기
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
# Summation
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:
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
오늘 사실 카카오 코딩테스트 보느라 이 문제밖에 풀지 못하였다.
이 문제는 투포인터를 활용하여 풀었는데, 점점 투포인터를 활용하는데 익숙해지고있다.
투포인터는 명확히 정의되지는 않았지만 유용하게 쓰이는 알고리즘 문제 해결 전략으로 익히 알려져있다.
Written with StackEdit.
'Python > Problem Solving' 카테고리의 다른 글
[TIL] 👨💻파이썬 알고리즘 인터뷰 Day_2 # 배열 빗물 트래핑 (0) | 2020.09.12 |
---|---|
[TIL] 파이썬 알고리즘 인터뷰 Day_1 # 1 문자열 조작 (0) | 2020.09.11 |
백준 2231번 분해합 [브루트포스] (0) | 2020.09.07 |
백준10773번 Stack활용 (0) | 2020.05.31 |