[leetcode] 15. 3Sum
2022. 11. 3. 18:27ㆍ노트/Algorithm : 알고리즘
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
for i in range(len(nums)-2):
for j in range(i+1, len(nums)-1):
for k in range(j+1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
res.append(sorted([nums[i], nums[j] , nums[k]]))
return list(set(map(tuple, res)))
=> 브루트포스 방식 : Timeout
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
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:
sums = nums[i] + nums[left] + nums[right]
if sums < 0:
left += 1
elif sums > 0:
right -= 1
else: # 정답 #
result.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 result
--> Twopoint 방식
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 121. Best Time to Buy and Sell Stock (0) | 2022.11.08 |
---|---|
[leetcode] 561. Array Partition (0) | 2022.11.04 |
[leetcode] 42. Trapping Rain Water (0) | 2022.11.02 |
리스트에서 최솟값 찾기 구현 (0) | 2021.08.11 |
[leetcode] 21. Merge Two Sorted Lists (0) | 2021.08.10 |