[코테] 리트코드 배열 15. 3Sum
15. 3Sum
문제 링크
https://leetcode.com/problems/3sum/description/
문제 설명
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
제한 사항
- 3 <= nums.length <= 3000
- -105 <= nums[i] <= 105
입출력 예 #1
- Input: nums = [-1,0,1,2,-1,-4]
- Output: [[-1,-1,2],[-1,0,1]]
- Explanation:
- nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
- nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
- nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
입출력 예 #2
- Input: nums = [0,1,1]
- Output: []
- Explanation: The only possible triplet does not sum up to 0.
입출력 예 #3
- Input: nums = [0,0,0]
- Output: [[0,0,0]]
- Explanation: The only possible triplet sums up to 0.
문제 풀이
브루트포스 방식으로 진행 시 시간초과로 FAIL됨
투 포인터 방식으로 하면 O(n^2)내로 풀 수 있음
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
results = []
nums.sort()
for i in range(0, len(nums)-2):
# 중복된 값 건너뛰기
if i > 0 and nums[i] == nums[i-1] :
continue
# 간격을 좁혀가며 합 sum 계산
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인 경우이므로 정답 및 스킵 처리
results.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 results
Comments