Skip to content

Commit

Permalink
feat: 15. 3Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
HodaeSsi committed Dec 21, 2024
1 parent 116e233 commit 5f66937
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions 3sum/HodaeSsi.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
# 시간복잡도 O(n^2), 공간복잡도 O(n^2)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# key: 값, value: list((i, j))
dic = {}
answer = set()
answerSet = set()
nums.sort()

# 이중 for문으로 모든 경우의 수를 구합니다.
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] in dic:
dic[nums[i] + nums[j]].append((i, j))
for i in range(len(nums) - 2):
leftIdx = i + 1
rightIdx = len(nums) - 1
while leftIdx < rightIdx:
sum = nums[i] + nums[leftIdx] + nums[rightIdx]
if sum < 0:
leftIdx += 1
elif sum > 0:
rightIdx -= 1
else:
dic[nums[i] + nums[j]] = [(i, j)]
answerSet.add((nums[i], nums[leftIdx], nums[rightIdx]))
leftIdx = leftIdx + 1
rightIdx = rightIdx - 1

for k in range(len(nums)):
for i, j in dic.get(-nums[k], []):
if i != k and j != k:
answer.add(tuple(sorted([nums[i], nums[j], nums[k]])))

return list(answer)

return list(answerSet)

0 comments on commit 5f66937

Please sign in to comment.