-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathsolution.go
More file actions
39 lines (33 loc) · 654 Bytes
/
solution.go
File metadata and controls
39 lines (33 loc) · 654 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
package main
import (
"sort"
)
func threeSum(nums []int) [][]int {
var res [][]int
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
if i == 0 || (i > 0 && nums[i] != nums[i-1]) {
low := i + 1
high := len(nums) - 1
sum := 0 - nums[i]
for low < high {
if (nums[low] + nums[high]) == sum {
res = append(res, []int{nums[i], nums[low], nums[high]})
for low < high && nums[low] == nums[low+1] {
low++
}
for low < high && nums[high] == nums[high-1] {
high--
}
low++
high--
} else if nums[low]+nums[high] > sum {
high--
} else {
low++
}
}
}
}
return res
}