package main
// 16最接近的三数之和
// 给你一个长度为 n 的整数数组 nums 和 一个目标值 target。
// 请你从 nums 中选出三个整数,使它们的和与 target 最接近。
// 返回这三个数的和。
// 假定每组输入只存在恰好一个解。
// 示例 1:
// 输入:nums = [-1,2,1,-4], target = 1
// 输出:2
// 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
func threeSumClosest(nums []int, target int) int {
// 思路 排序+双指针
sort.Ints(nums)
n := len(nums)
//取最大值
closeSum := math.MaxInt32
// 枚举变量a 范围为 a ~ n ~ 3
for i := 0; i < n-2; i++ {
//双指针初始化
left, right := i + 1, n - 1
//循环遍历双指针
for left < right {
// sum三数字和为
sum := nums[i] + nums[left] + nums[right]
//如果接近就更新这个
if abs(target - sum) < abs(target - closeSum) {
//更新
closeSum = sum
}
// 说明数字小了 左指针++
if sum < target {
left++
//说明数字大了 right--
} else if sum > target {
right--
} else {
//找到返回
return sum
}
}
}
return closeSum
}
// 绝对值
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// 测试
func main() {
testCases := []struct {
nums []int
target int
expect int
}{
{[]int{-1, 2, 1, -4}, 1, 2},
{[]int{0, 0, 0}, 1, 0},
{[]int{1, 1, -1, -1, 3}, -1, -1},
}
for _, tx := range testCases {
result := threeSumClosest(tx.nums, tx.target)
fmt.Printf("Input: nums = %v, target = %d\n", tx.nums, tx.target)
fmt.Printf("Output: %d, Expected: %d\n", result, tx.expect)
fmt.Println()
}
}
leetcode-16题最接近的三数之和
于 2024-06-24 21:00:16 首次发布