1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
// 两数之和解法
func threeSum(nums []int) [][]int {
var res [][]int
if len(nums) < 3 {
return res
}
sort.Ints(nums)
cache := make(map[string]struct{})
for index := 0; index < len(nums); index++ {
twoRes := myTwoSum(nums[index+1:], -nums[index])
for _, values := range twoRes {
if _, ok := cache[fmt.Sprintf("%d,%d,%d", nums[index], values[0], values[1])]; !ok {
cache[fmt.Sprintf("%d,%d,%d", nums[index], values[0], values[1])] = struct{}{}
res = append(res, []int{nums[index], values[0], values[1]})
}
}
}
return res
}
func myTwoSum(nums []int, target int) [][]int {
var res [][]int
cache := make(map[int]struct{})
for index := 0; index < len(nums); index++ {
if _, ok := cache[target-nums[index]]; ok {
res = append(res, []int{nums[index], target - nums[index]})
} else {
cache[nums[index]] = struct{}{}
}
}
return res
}
// 夹逼法解法
func threeSum(nums []int) [][]int {
var res [][]int
if len(nums) < 3 {
return res
}
sort.Ints(nums)
cache := make(map[string]struct{})
for index := 0; index < len(nums)-2; index++ {
left, right := index+1, len(nums)-1
for left < right {
sum := nums[index] + nums[left] + nums[right]
if sum == 0 {
if _, ok := cache[fmt.Sprintf("%d,%d,%d", nums[index], nums[left], nums[right])]; !ok {
cache[fmt.Sprintf("%d,%d,%d", nums[index], nums[left], nums[right])] = struct{}{}
res = append(res, []int{nums[index], nums[left], nums[right]})
}
right--
left++
} else if sum > 0 {
right--
} else {
left++
}
}
}
return res
}
|