File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ # Intuition
3+ 처음에는 1주차의 Two Sum 문제 풀이를 응용하여, 배열 순회 + 해시 테이블 만들어 값 찾기를 시도했으나
4+ 정렬 + 투포인터 풀이가 더 빠르므로 그렇게 제출했습니다.
5+
6+ # Approach
7+ nums 배열을 순회하면서 -nums[i]를 합으로 하는 두 수를 나머지 배열 부분에서 찾는다.
8+ 찾을 때는 정렬 & 투포인터를 활용하여 중복을 건너 뛰는 방식으로 속도를 높인다.
9+
10+
11+ # Complexity
12+ - Time complexity: 정렬 + 투포인터 이중 반복으로 O(N^2)
13+
14+ - Space complexity: 정렬 하는데에 O(N) , answer 배열 생성하는데에 O(M)
15+ """
16+
17+
18+ class Solution :
19+ def threeSum (self , nums : list [int ]) -> list [list [int ]]:
20+ nums .sort () # O(NlogN)
21+ n = len (nums )
22+ answer = []
23+
24+ for i in range (n - 2 ): # 이중 반복문 O(N^2)
25+ # 중복 제거
26+ if i > 0 and nums [i ] == nums [i - 1 ]:
27+ continue
28+
29+ # nums[i]가 0보다 크면 뒤도 다 양수라 종료 가능
30+ if nums [i ] > 0 :
31+ break
32+
33+ left , right = i + 1 , n - 1
34+
35+ while left < right :
36+ total = nums [i ] + nums [left ] + nums [right ]
37+
38+ if total == 0 :
39+ answer .append ([nums [i ], nums [left ], nums [right ]])
40+ left += 1
41+ right -= 1
42+
43+ # left/right 중복 제거
44+ while left < right and nums [left ] == nums [left - 1 ]:
45+ left += 1
46+ while left < right and nums [right ] == nums [right + 1 ]:
47+ right -= 1
48+
49+ elif total < 0 :
50+ left += 1
51+ else :
52+ right -= 1
53+
54+ return answer
You can’t perform that action at this time.
0 commit comments