Leetcode - 15. 3Sum
Leetcode - 15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Solution
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
func threeSum(nums []int) [][]int {
sort.Ints(nums)
res := [][]int{}
for ind, val := range nums {
if ind > 0 && val == nums[ind-1] {
continue
}
left, right := ind+1, len(nums)-1
for left < right {
total := val + nums[left] + nums[right]
if total > 0 {
right -= 1
} else if total < 0 {
left += 1
} else {
res = append(res, []int{val, nums[left], nums[right]})
left += 1
for nums[left] == nums[left-1] && left < right {
left += 1
}
}
}
}
return res
}
This post is licensed under CC BY 4.0 by the author.