-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathN015ThreeSum.go
More file actions
50 lines (45 loc) · 753 Bytes
/
N015ThreeSum.go
File metadata and controls
50 lines (45 loc) · 753 Bytes
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
package main
import "sort"
type N015ThreeSum struct {
}
func (this *N015ThreeSum) threeSum(nums []int) [][]int {
sort.Ints(nums)
result := make([][]int, 0)
size := len(nums)
if size <= 2 {
return result
}
var n1, n2, n3, sum int
for i := 0; i < size-2; {
n1 = nums[i]
if n1 > 0 {
break
}
for j, k := i+1, size-1; j < k; {
n2 = nums[j]
n3 = nums[k]
sum = n1 + n2 + n3
if sum > 0 {
k--
} else if sum < 0 {
j++
} else {
j++
for nums[j] == nums[j-1] && j < k {
j++
}
k--
for nums[k] == nums[k+1] && k > j {
k--
}
triplet := []int{n1, n2, n3}
result = append(result, triplet)
}
}
i++
for nums[i] == nums[i-1] && i < size-2 {
i++
}
}
return result
}