15 3sum
·data-structure-and-algorithm
#hash-table
15. 三数之和
go:
import "sort"
func threeSum(nums []int) [][]int {
sort.Ints(nums)
var results [][]int
length := len(nums)
for i := 0; i < length - 2; i++ {
if i > 0 && nums[i] == nums[i - 1] {
continue
}
target := -nums[i]
left := i + 1
right := length - 1
for left < right {
sum := nums[left] + nums[right]
if sum < target {
left++
} else if sum > target {
right--
} else {
results = append(results, []int{nums[i], nums[left], nums[right]})
for left < right && nums[left] == nums[left + 1] {
left++
}
for left < right && nums[right] == nums[right - 1] {
right--
}
left++
right--
}
}
}
return results
}