|
| 1 | +// 시간복잡도: O(n^2) |
| 2 | +// 공간복잡도: O(n) |
| 3 | + |
| 4 | +package main |
| 5 | + |
| 6 | +import ( |
| 7 | + "sort" |
| 8 | + "testing" |
| 9 | +) |
| 10 | + |
| 11 | +func TestThreeSum(t *testing.T) { |
| 12 | + test1 := []int{-1, 0, 1, 2, -1, -4} |
| 13 | + result1 := threeSum(test1) |
| 14 | + |
| 15 | + for _, comp := range result1 { |
| 16 | + for _, num := range comp { |
| 17 | + t.Logf("%d ", num) |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + println("YO") |
| 22 | + |
| 23 | + if len(result1) != 2 { |
| 24 | + t.Errorf("Expected 2, got %d", len(result1)) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func twoSum(nums []int, target int) [][]int { |
| 29 | + result := [][]int{} |
| 30 | + seen := map[int]int{} |
| 31 | + for i, num := range nums { |
| 32 | + complement := target - num |
| 33 | + if _, ok := seen[complement]; ok { |
| 34 | + result = append(result, []int{seen[complement], i}) |
| 35 | + } |
| 36 | + seen[num] = i |
| 37 | + } |
| 38 | + |
| 39 | + return result |
| 40 | +} |
| 41 | + |
| 42 | +func threeSum(nums []int) [][]int { |
| 43 | + result := map[int]map[int]map[int]bool{} |
| 44 | + |
| 45 | + for i, num := range nums[:len(nums)-2] { |
| 46 | + if (i > 0 && num == nums[i-1]) { |
| 47 | + continue |
| 48 | + } |
| 49 | + for _, comp := range twoSum(nums[i+1:], 0-num) { |
| 50 | + comps := []int{num, nums[comp[0]+i+1], nums[comp[1]+i+1]} |
| 51 | + sort.Ints(comps) |
| 52 | + comp1 := comps[0] |
| 53 | + comp2 := comps[1] |
| 54 | + comp3 := comps[2] |
| 55 | + if _, ok := result[comp1]; !ok { |
| 56 | + result[comp1] = map[int]map[int]bool{} |
| 57 | + } |
| 58 | + if _, ok := result[comp1][comp2]; !ok { |
| 59 | + result[comp1][comp2] = map[int]bool{} |
| 60 | + } |
| 61 | + result[comp1][comp2][comp3] = true |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + answers := [][]int{} |
| 68 | + for key1 := range result { |
| 69 | + |
| 70 | + for key2 := range result[key1] { |
| 71 | + for key3 := range result[key1][key2] { |
| 72 | + comp := []int{key1, key2, key3} |
| 73 | + answers = append(answers, comp) |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return answers |
| 79 | +} |
0 commit comments