package main
import (
"fmt"
"math"
"sort"
)
func main() {
var slice1 = make([]int, 0, 5)
fmt.Println("please input an array: ")
for i := 1; true; i++ {
var inputNum int
fmt.Printf("No.%d : ", i)
_, err := fmt.Scanf("%d", &inputNum)
if nil == err {
slice1 = append(slice1, inputNum)
} else {
break
}
}
printSlice(slice1)
var target int
fmt.Println("please input the target: ")
fmt.Scanf("%d", &target)
fmt.Println(threeSumClosed(slice1, target))
}
func printSlice(x []int){
fmt.Printf("slice=%v len=%d cap=%d \n",x,len(x),cap(x))
}
func threeSumClosed(nums []int, target int) int {
sort.Ints(nums)
totalLenth := len(nums)
best := math.MaxInt32
update := func(cur int) {
if abs(cur - target) < abs(best - target) {
best = cur
}
}
for left := 0; left < totalLenth - 1; left++ {
if (left > 0) && (nums[left] == nums[left + 1]) {
continue
}
mid, right := left + 1, totalLenth - 1
for mid < right {
sum := nums[left] + nums[mid] + nums[right]
if sum == target {
return target
}
update(sum)
if sum > target {
right0 := right - 1
if (mid < right0) && (nums[right0] == nums[right]) {
right0--
}
right = right0
} else {
mid0 := mid + 1
if (mid0 < right) && (nums[mid0] == nums[mid]) {
mid0++
}
mid = mid0
}
}
}
return best
}
func abs(a int) int {
if(a < 0) {
return -1*a
}
return a
}
力扣算法——第16题——go语言
最新推荐文章于 2024-11-07 23:56:43 发布