- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path15.threeSum.go
58 lines (53 loc) · 1.05 KB
/
15.threeSum.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
package myarray
import"sort"
functhreeSum(nums []int) [][]int {
varres [][]int
length:=len(nums)
iflength<3 {
returnres
}
// 排序
sort.Ints(nums)
fori:=0; i<length; i++ {
// 如果当前数字大于0,则三数之和一定大于0,所以结束循环
ifnums[i] >0 {
break
}
// 去重
ifi>0&&nums[i] ==nums[i-1] {
continue
}
L, R:=i+1, length-1
// fmt.Printf("i:%d->%d L:%d->%d R:%d->%d sum:%d\n",
// i, nums[i], L, nums[L], R, nums[R], nums[i]+nums[L]+nums[R])
forL<R {
sum:=nums[i] +nums[L] +nums[R]
switch {
casesum<0:
L++
casesum>0:
R--
default:
res=append(res, []int{nums[i], nums[L], nums[R]})
// 为避免重复添加,L 和 R 都需要移动到不同的元素上
L, R=next(nums, L, R)
}
} // end inner for
} // end outer for
returnres
}
funcnext(nums []int, L, Rint) (int, int) {
forL<R {
switch {
casenums[L] ==nums[L+1]:
L++
casenums[R] ==nums[R-1]:
R--
default:
L++
R--
returnL, R
}
}
returnL, R
}