-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15-3Sum.go
More file actions
45 lines (38 loc) · 744 Bytes
/
Copy path15-3Sum.go
File metadata and controls
45 lines (38 loc) · 744 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
func threeSum(nums []int) [][]int {
n := len(nums)
res := [][]int{}
if n < 3 {
return res
}
// We sort it so when we move in the array we know for sure that left is less and right is high, if not the same number
sort.Ints(nums)
for i := 0; i < n-2; i++ {
if nums[i] > 0 {
break
}
if i > 0 && nums[i] == nums[i-1] {
continue
}
l := i + 1
r := n - 1
for l < r {
sum := nums[i] + nums[l] + nums[r]
if sum < 0 {
l++
} else if sum > 0 {
r--
} else {
res = append(res, []int{nums[i], nums[l], nums[r]})
// Skip duplicates
lVal, rVal := nums[l], nums[r]
for l < r && nums[l] == lVal {
l++
}
for l < r && nums[r] == rVal {
r--
}
}
}
}
return res
}