LeetCode 题解工作台
最接近的三数之和
给你一个长度为 n 的整数数组 nums 和 一个目标值 target 。请你从 nums 中选出三个在 不同下标位置 的整数,使它们的和与 target 最接近。 返回这三个数的和。 假定每组输入只存在恰好一个解。 示例 1: 输入: nums = [-1,2,1,-4], target = 1 …
3
题型
9
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们将数组排序,然后遍历数组,对于每个元素 ,我们使用指针 和 分别指向 和 ,计算三数之和,如果三数之和等于 ,则直接返回 ,否则根据与 的差值更新答案。如果三数之和大于 ,则将 向左移动一位,否则将 向右移动一位。 时间复杂度 ,空间复杂度 $O(\log n)$。其中 为数组长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个在 不同下标位置 的整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2)。
示例 2:
输入:nums = [0,0,0], target = 1 输出:0 解释:与 target 最接近的和是 0(0 + 0 + 0 = 0)。
提示:
3 <= nums.length <= 1000-1000 <= nums[i] <= 1000-104 <= target <= 104
解题思路
方法一:排序 + 双指针
我们将数组排序,然后遍历数组,对于每个元素 ,我们使用指针 和 分别指向 和 ,计算三数之和,如果三数之和等于 ,则直接返回 ,否则根据与 的差值更新答案。如果三数之和大于 ,则将 向左移动一位,否则将 向右移动一位。
时间复杂度 ,空间复杂度 。其中 为数组长度。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
ans = inf
for i, v in enumerate(nums):
j, k = i + 1, n - 1
while j < k:
t = v + nums[j] + nums[k]
if t == target:
return t
if abs(t - target) < abs(ans - target):
ans = t
if t > target:
k -= 1
else:
j += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you know how to handle cases where the array has both negative and positive numbers?
- question_mark
Can you explain the two-pointer strategy and how it minimizes the difference to the target?
- question_mark
Will you discuss the trade-offs between time complexity and the accuracy of finding the closest sum?
常见陷阱
外企场景- error
Forgetting to sort the array first, which can lead to inefficient solutions or missed results.
- error
Not properly managing pointer updates, potentially leading to incorrect triplets being selected.
- error
Overlooking edge cases such as when all numbers in the array are equal or when the target is very far from all possible sums.
进阶变体
外企场景- arrow_right_alt
3Sum problem, where you find an exact target sum with three numbers.
- arrow_right_alt
4Sum Closest problem, where you find four integers that sum closest to a given target.
- arrow_right_alt
3Sum with Multiplicity, where you find the number of distinct triplets that sum to the target.