-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path15. 3Sum.go
72 lines (67 loc) · 1.69 KB
/
15. 3Sum.go
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
62
63
64
65
66
67
68
69
70
71
72
package leetcode
import (
"sort"
)
// 解法一 最优解,双指针 + 排序
func threeSum(nums []int) [][]int {
sort.Ints(nums)
result, start, end, index, addNum, length := make([][]int, 0), 0, 0, 0, 0, len(nums)
for index = 1; index < length-1; index++ {
start, end = 0, length-1
if index > 1 && nums[index] == nums[index-1] {
start = index - 1
}
for start < index && end > index {
if start > 0 && nums[start] == nums[start-1] {
start++
continue
}
if end < length-1 && nums[end] == nums[end+1] {
end--
continue
}
addNum = nums[start] + nums[end] + nums[index]
if addNum == 0 {
result = append(result, []int{nums[start], nums[index], nums[end]})
start++
end--
} else if addNum > 0 {
end--
} else {
start++
}
}
}
return result
}
// 解法二
func threeSum1(nums []int) [][]int {
res := [][]int{}
counter := map[int]int{}
for _, value := range nums {
counter[value]++
}
uniqNums := []int{}
for key := range counter {
uniqNums = append(uniqNums, key)
}
sort.Ints(uniqNums)
for i := 0; i < len(uniqNums); i++ {
if (uniqNums[i]*3 == 0) && counter[uniqNums[i]] >= 3 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[i]})
}
for j := i + 1; j < len(uniqNums); j++ {
if (uniqNums[i]*2+uniqNums[j] == 0) && counter[uniqNums[i]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[j]})
}
if (uniqNums[j]*2+uniqNums[i] == 0) && counter[uniqNums[j]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[j], uniqNums[j]})
}
c := 0 - uniqNums[i] - uniqNums[j]
if c > uniqNums[j] && counter[c] > 0 {
res = append(res, []int{uniqNums[i], uniqNums[j], c})
}
}
}
return res
}