forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0015-3sum.go
39 lines (34 loc) · 916 Bytes
/
0015-3sum.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
func threeSum(nums []int) [][]int {
n := len(nums)
// Sort the given array
sort.Ints(nums)
var result [][]int
for num1Idx := 0; num1Idx < n-2; num1Idx++ {
// Skip all duplicates from left
// num1Idx>0 ensures this check is made only from 2nd element onwards
if num1Idx > 0 && nums[num1Idx] == nums[num1Idx-1] {
continue
}
num2Idx := num1Idx + 1
num3Idx := n - 1
for num2Idx < num3Idx {
sum := nums[num2Idx] + nums[num3Idx] + nums[num1Idx]
if sum == 0 {
// Add triplet to result
result = append(result, []int{nums[num1Idx], nums[num2Idx], nums[num3Idx]})
num3Idx--
// Skip all duplicates from right
for num2Idx < num3Idx && nums[num3Idx] == nums[num3Idx+1] {
num3Idx--
}
} else if sum > 0 {
// Decrement num3Idx to reduce sum value
num3Idx--
} else {
// Increment num2Idx to increase sum value
num2Idx++
}
}
}
return result
}