๊ฐ๋ฐ/๐ค ์๊ณ ๋ฆฌ์ฆ
[leetcode] 15. 3Sum ํ์ด, ํด์ค (python)
ttoance
2023. 10. 28. 21:09
https://leetcode.com/problems/3sum/
1์ฐจ ํ์ด
์ ๊ทผ๋ฒ์ ๋ชป์ฐพ์์ O(n*n)์ผ๋ก ํธ๋ ๋ฐฉ๋ฒ์ ์๋ํ๋ค.
a,b๋ฅผ ์ฐพ์์ -(a + b)๊ฐ์ด ๋ค๋ฅธ ๋ฐฐ์ด์์ ์๋์ง ํ์ธํ๋ ๋ฐฉ๋ฒ์ด์๋ค.
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
dset = set()
for num in nums:
if num not in dset:
dset.add(num)
result = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
check = nums[i] + nums[j]
if -check in dset and nums.index(-check) not in [i, j]:
# ์ค๋ณต๊ฐ ์ฒดํฌ ์ํด ์ ๋ ฌํด์ ํค๋ฅผ ์์ฑ
r = tuple(sorted([nums[i], nums[j], -check]))
result.add(r)
return result
2์ฐจ ํ์ด
์ด ์๊ฐ์ด๊ณผ๋ฅผ ํด๊ฒฐํ๊ณ ์, ์ด๋ฏธ ํ์ธํ ๊ฐ์ ๋ํด์๋ ๋์ด๊ฐ๋ ๋ก์ง์ ์ถ๊ฐํ๋ค.
๊ทธ๋ฌ๋๋ ์๊ฐ์ด๊ณผ๋ ํด๊ฒฐ์ด ๋์๋ค.
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
dset = defaultdict(list)
for i, num in enumerate(nums):
dset[num].append(i)
result = set()
# ์๊ฐ ์ค์ด๊ธฐ ์ํด ์ฒดํฌํ ๊ฐ์ ๋ํด์ ๊ฒฐ๊ณผ๊ฐ ์ ์ฅ
checked = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
check = nums[i] + nums[j]
if (nums[i], nums[j]) in checked:
continue
if -check in dset:
# i,j ์กฐ๊ฑด ํ์ธ
if dset[-check] == [i] or dset[-check] == [j] or dset[-check] == [i,j] or dset[-check] == [j, j]:
continue
# ์ค๋ณต๊ฐ ์ฒดํฌ ์ํด ์ ๋ ฌํด์ ํค๋ฅผ ์์ฑ
r = tuple(sorted([nums[i], nums[j], -check]))
result.add(r)
# ์๊ฐ ์ด๊ณผ ํด๊ฒฐํ๊ธฐ ์ํด ์ ์ฅํด๋
checked.add((nums[i], nums[j]))
return result
ํด์ค
https://www.youtube.com/watch?v=jzZsG8n2R9A
res = []
nums.sort()
for i, a in enumerate(nums):
if i > 0 and a == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
threeSum = a + nums[l] + nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
res.append([a, nums[l], nums[r]])
l += 1
while nums[l] == nums[l - 1] and l < r:
l += 1
return res
์ฐธ๊ณ ๋ก, ํด์ค์ ์ฌ๊ธฐ ๋ฐฉ๋ฒ๊ณผ ์ ์ฌํ ์ ๊ทผ์ผ๋ก ๋ฌธ์ ๋ฅผ ํ์๋ค.
https://ddoance.tistory.com/149
๋ฐ์ํ