feat: three sum
This commit is contained in:
41
pkg/three_sum/main.go
Normal file
41
pkg/three_sum/main.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package three_sum
|
||||
|
||||
import (
|
||||
"slices"
|
||||
)
|
||||
|
||||
func TwoSum(numbers []int, target int, solutions map[[3]int]bool) {
|
||||
start := 0
|
||||
end := len(numbers) - 1
|
||||
|
||||
for start < end {
|
||||
sum := numbers[start] + numbers[end]
|
||||
|
||||
if sum < target {
|
||||
start++
|
||||
} else if sum > target {
|
||||
end--
|
||||
} else {
|
||||
solutions[[3]int{-target, numbers[start], numbers[end]}] = true
|
||||
start++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ThreeSum(nums []int) [][]int {
|
||||
slices.Sort(nums)
|
||||
|
||||
solutions := map[[3]int]bool{}
|
||||
|
||||
for i := range nums {
|
||||
TwoSum(nums[i+1:], -nums[i], solutions)
|
||||
}
|
||||
|
||||
result := [][]int{}
|
||||
|
||||
for solution := range solutions {
|
||||
result = append(result, solution[:])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user