原题链接15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题思路:转化为n个2sum问题
func threeSum(nums []int) [][]int {
var res [][]int
sort.Ints(nums)
lg := len(nums)
for i := 0; i < lg-2; i++ {
l := i + 1
r := lg - 1
if i > 0 && nums[i] == nums[i-1] {
continue
}
for l < r {
if nums[i]+nums[l]+nums[r] == 0 {
res = append(res, []int{nums[i], nums[l], nums[r]})
l++
r--
for l < r && nums[l] == nums[l-1] {
l++
}
for l < r && nums[r] == nums[r+1] {
r--
}
} else if nums[i]+nums[l]+nums[r] < 0 {
l++
} else {
r--
}
}
}
return res
}
有疑问加站长微信联系(非本文作者)