File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ // 풀이
2+ // 배열을 정렬하고
3+ // two pointer 사용
4+
5+ // TC
6+ // 정렬 O(nlogn) + Two pointer 이중 루프 O(n^2) = O(n^2)
7+
8+ // SC
9+ // Go의 sort.Ints()는 TimSort를 사용.
10+ // Merge Sort와 Insertion Sort의 조합으로 동작.
11+ // 정렬 O(n) + Two pointer O(1) + 결과 배열 O(n) = O(n)
12+
13+ func threeSum (nums []int ) [][]int {
14+ result := [][]int {}
15+ sort .Ints (nums ) // nums를 정렬
16+
17+ for i := 0 ; i < len (nums )- 2 ; i ++ {
18+ if i > 0 && nums [i ] == nums [i - 1 ] {
19+ continue // 중복된 값 건너뜀
20+ }
21+
22+ left , right := i + 1 , len (nums )- 1
23+ for left < right {
24+ sum := nums [i ] + nums [left ] + nums [right ]
25+ if sum == 0 {
26+ result = append (result , []int {nums [i ], nums [left ], nums [right ]})
27+ left ++
28+ right --
29+
30+ // 중복 제거
31+ for left < right && nums [left ] == nums [left - 1 ] {
32+ left ++
33+ }
34+ for left < right && nums [right ] == nums [right + 1 ] {
35+ right --
36+ }
37+ } else if sum < 0 {
38+ left ++
39+ } else {
40+ right --
41+ }
42+ }
43+ }
44+
45+ return result
46+ }
You can’t perform that action at this time.
0 commit comments