|
| 1 | +""" |
| 2 | +# Intuition |
| 3 | +- |
| 4 | +
|
| 5 | +# Approach |
| 6 | +index가 모두 다를것, |
| 7 | +합 = 0 -> -a = b+c |
| 8 | +중복 X -> set : dic와 다르게 가변객체 삽입 X |
| 9 | +Two Pointer -> 정렬된 배열을 활용 |
| 10 | +
|
| 11 | +# Complexity |
| 12 | +- Time complexity |
| 13 | + - Brute-force : O(N^3) |
| 14 | + - Set : O(N^2) - Time Limit Exceeded (memory??) |
| 15 | + - Two Pointer : O(N^2) |
| 16 | +
|
| 17 | +- Space complexity |
| 18 | + - Brute-force : O(N) |
| 19 | + - Set : O(N) |
| 20 | + - Two Pointer : O(1) |
| 21 | +""" |
| 22 | + |
| 23 | +from typing import List |
| 24 | + |
| 25 | + |
| 26 | +class Solution: |
| 27 | + def threeSum(self, nums: List[int]) -> List[List[int]]: |
| 28 | + |
| 29 | + triplets = set() |
| 30 | + nums.sort() # O(NlogN), return None |
| 31 | + |
| 32 | + for i in range(len(nums) - 2): # O(N) |
| 33 | + low, high = i + 1, len(nums) - 1 |
| 34 | + |
| 35 | + while low < high: # O(N) |
| 36 | + three_sum = nums[i] + nums[low] + nums[high] |
| 37 | + |
| 38 | + if three_sum < 0: |
| 39 | + low += 1 |
| 40 | + elif three_sum > 0: |
| 41 | + high -= 1 |
| 42 | + else: |
| 43 | + triplets.add((nums[i], nums[low], nums[high])) |
| 44 | + low, high = low + 1, high - 1 |
| 45 | + |
| 46 | + return list(triplets) |
| 47 | + |
| 48 | + |
| 49 | +""" Set |
| 50 | +class Solution: |
| 51 | + def threeSum(self, nums: List[int]) -> List[List[int]]: |
| 52 | +
|
| 53 | + triplets = set() |
| 54 | +
|
| 55 | + for i in range(len(nums) - 2): |
| 56 | + seen = set() |
| 57 | +
|
| 58 | + for j in range(i + 1, len(nums)): |
| 59 | + complement = -(nums[i] + nums[j]) |
| 60 | +
|
| 61 | + if complement in seen: |
| 62 | + triplets.add(tuple(sorted([nums[i], nums[j], complement]))) |
| 63 | +
|
| 64 | + seen.add(nums[j]) |
| 65 | +
|
| 66 | + return list(triplets) |
| 67 | +""" |
| 68 | + |
| 69 | +""" Brute-force |
| 70 | +class Solution: |
| 71 | + def threeSum(self, nums: List[int]) -> List[List[int]]: |
| 72 | +
|
| 73 | + n = len(nums) |
| 74 | + result = [] |
| 75 | +
|
| 76 | + for i in range(n-2): |
| 77 | + for j in range(i+1, n-1): |
| 78 | + for k in range(j+1, n): |
| 79 | + if i != j and i != k and j != k: |
| 80 | + |
| 81 | + if nums[i] + nums[j] + nums[k] == 0: |
| 82 | + li = sorted([nums[i], nums[j], nums[k]]) |
| 83 | +
|
| 84 | + if li not in result: # O(L) |
| 85 | + result.append(li) |
| 86 | +
|
| 87 | + return result |
| 88 | +""" |
| 89 | + |
| 90 | +nums = [-1, 0, 1, 2, -1, -4] |
| 91 | +sol = Solution() |
| 92 | + |
| 93 | +print(sol.threeSum(nums)) |
| 94 | +# [[-1,-1,2],[-1,0,1]] |
| 95 | + |
| 96 | +# print(len({1, 1, 2})) # 2 |
0 commit comments