难度:中等 题目来源:力扣(LeetCode) https://leetcode-cn.com/problems/3sum
说明:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4]
,
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法:
import "sort"
func threeSum(nums []int) [][]int {
ret := make([][]int, 0, len(nums))
if len(nums) < 3 {
return ret
}
sort.Ints(nums)
for index, value := range nums {
if index > len(nums)-3 || value > 0 || (value+nums[index+1]) > 0 {
break
}
if index > 0 && value == nums[index-1] {
continue
}
leftIndex, rightIndex := index+1, len(nums)-1
for leftIndex < rightIndex {
leftValue, rightValue := nums[leftIndex], nums[rightIndex]
if leftIndex != index+1 && leftValue == nums[leftIndex-1] {
leftIndex++
continue
}
if rightIndex != len(nums)-1 && rightValue == nums[rightIndex+1] {
rightIndex--
continue
}
v := value + leftValue + rightValue
if v > 0 {
rightIndex--
} else if v < 0 {
leftIndex++
} else {
ret = append(ret, []int{value, leftValue, rightValue})
leftIndex++
rightIndex--
}
}
}
return ret
}