File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * TC: O(N^2)
3
+ * SC: O(N)
4
+ *
5
+ * 풀이
6
+ * 2sum의 확장 문제 (nums[i] == nums[j] + nums[k])
7
+ * 2sum은 투포인터로 시간복잡도 O(N)을 만들기 위해 투포인터를 활용한다.
8
+ */
9
+
10
+ /**
11
+ * @param {number[] } nums
12
+ * @return {number[][] }
13
+ */
14
+ var threeSum = function ( nums ) {
15
+ const result = [ ] ;
16
+ const sortedNums = nums . sort ( ( a , b ) => a - b ) ;
17
+
18
+ // 3개 항의 합이 0이 될 수 없는 경우
19
+ if ( sortedNums [ 0 ] > 0 || sortedNums [ sortedNums . length - 1 ] < 0 ) {
20
+ return [ ] ;
21
+ }
22
+
23
+ // 1. 순회를 하며 2sum의 target 값을 지정함
24
+ for ( let index = 0 ; index < sortedNums . length - 2 ; ) {
25
+ twoSum ( index + 1 , sortedNums [ index ] ) ;
26
+ // 3. 동일한 숫자를 제외하기 위해 순회
27
+ while ( sortedNums [ index ] === sortedNums [ index + 1 ] ) {
28
+ index += 1 ;
29
+ }
30
+ index += 1 ;
31
+ }
32
+
33
+ return result ;
34
+
35
+ function twoSum ( startIndex , target ) {
36
+ let left = startIndex ;
37
+ let right = sortedNums . length - 1 ;
38
+
39
+ // 2. 투포인터로 2sum이 target이 되는 경우를 찾기 위해 순회
40
+ while ( left < right ) {
41
+ const sum = sortedNums [ left ] + sortedNums [ right ] ;
42
+
43
+ if ( sum + target === 0 ) {
44
+ result . push ( [ target , sortedNums [ left ] , sortedNums [ right ] ] ) ;
45
+ }
46
+
47
+ if ( sum + target < 0 ) {
48
+ while ( sortedNums [ left ] === sortedNums [ left + 1 ] ) {
49
+ left += 1 ;
50
+ }
51
+ left += 1 ;
52
+ } else {
53
+ while ( sortedNums [ right ] === sortedNums [ right - 1 ] ) {
54
+ right -= 1 ;
55
+ }
56
+ right -= 1 ;
57
+ }
58
+ }
59
+ }
60
+ } ;
You can’t perform that action at this time.
0 commit comments