-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy paththree_sum.go
More file actions
42 lines (39 loc) · 740 Bytes
/
three_sum.go
File metadata and controls
42 lines (39 loc) · 740 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
package main
import "fmt"
import "sort"
func threeSum(nums []int) [][]int {
var res [][]int
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
l := i + 1
r := len(nums) - 1
for l < r {
s := nums[i] + nums[l] + nums[r]
if s > 0 {
r--
} else if s < 0 {
l++
} else {
res = append(res, []int{nums[i], nums[l], nums[r]})
for l < r && nums[l] == nums[l+1] {
l++
}
for l < r && nums[r] == nums[r-1] {
r--
}
l++
r--
}
}
}
return res
}
func main() {
x := []int{-1, 0, 1, 2, -1, -4}
fmt.Println("input: ", x)
fmt.Println("output should be: ", [][]int{{-1, -1, 2}, {-1, 0, 1}})
fmt.Println("output: ", threeSum(x))
}