-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.go
More file actions
58 lines (56 loc) · 1.77 KB
/
Copy path15.go
File metadata and controls
58 lines (56 loc) · 1.77 KB
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
package main
import "sort"
func threeSum(nums []int) [][]int {
if len(nums) < 3 {
return [][]int{}
}
ret := [][]int{}
sort.Ints(nums)
for i := 0; i <= len(nums) - 3; i ++ {
if nums[i] > 0 {
break;
}
if i == 0 || nums[i] != nums[i - 1] {
left := i + 1
right := len(nums) - 1
for left < right {
// fmt.Println(i, left, right, ret)
if nums[i] + nums[left] + nums[right] == 0 {
ret = append(ret, []int{nums[i], nums[left], nums[right]})
left ++
right --
for left < right {
if nums[left] != nums[left - 1] && nums[right] != nums[right + 1] {
break
}
if nums[left] == nums[left - 1] {
left ++
}
if nums[right] == nums[right + 1] {
right --
}
}
} else if nums[i] + nums[left] + nums[right] < 0 {
left ++
for left < right {
if nums[left] == nums[left - 1] {
left ++
} else {
break;
}
}
} else {
right --
for right > left {
if nums[right] == nums[right + 1] {
right --
} else {
break;
}
}
}
}
}
}
return ret
}