File tree Expand file tree Collapse file tree 1 file changed +25
-4
lines changed Expand file tree Collapse file tree 1 file changed +25
-4
lines changed Original file line number Diff line number Diff line change 3
3
1. 3 <= nums.length <= 3000
4
4
2. -10^5 <= nums[i] <= 10^5
5
5
6
- Time Complexity:
7
- - O(n^2) (정렬은 O(n log n), 이중 반복문은 O(n^2))
8
- Space Complexity:
9
- - O(n) (결과 리스트)
6
+ Time Complexity: O(n^2)
7
+ - 정렬은 O(n log n), 이중 반복문은 O(n^2)
8
+ Space Complexity: O(n)
9
+ - 결과 리스트를 저장하는 데 필요한 공간
10
+
11
+ 풀이 방법:
12
+ - 투 포인터를 활용하여 합이 0이 되는 세 수 조합 찾기
13
+ - 배열 정렬: 투 포인터 사용 + 중복 처리 용이
14
+ - for 루프: 첫 번째 숫자 선택 (len(nums)-2까지)
15
+ - 중복된 첫 번째 숫자 건너뛰기
16
+ - left, right 포인터 설정
17
+ - while 루프: 두 포인터가 교차하지 않아야 함
18
+ - sum = nums[i] + nums[left] + nums[right] 계산
19
+ - sum == 0: 결과 추가, 중복 건너뛰기, 양쪽 포인터 이동
20
+ - sum < 0: left 증가 (더 큰 값 필요)
21
+ - sum > 0: right 감소 (더 작은 값 필요)
22
+ - 최종 결과 반환
10
23
"""
24
+ # Brute-force: three nested loops → O(n^3)
25
+ # Optimized: sort + two pointer → O(n^2)
11
26
12
27
class Solution :
13
28
def threeSum (self , nums : List [int ]) -> List [List [int ]]:
29
+ # Step 1: Sort the array
30
+ # Step 2: Fix one number using for loop
31
+ # Step 3: Use two pointers to find two other numbers
32
+ # - if sum == 0: valid triplet
33
+ # - if sum < 0: move left pointer
34
+ # - if sum > 0: move right pointer
14
35
nums .sort ()
15
36
result = []
16
37
You can’t perform that action at this time.
0 commit comments