Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
这道题要求在数组中找出三个数,使它们的和最接近目标值。经典做法是先排序,再固定一个数,使用左右双指针在剩余区间中逼近目标;每次比较当前三数和与 target 的差值,更新最优答案并根据大小移动指针。这样可以将暴力的 O(n^3) 优化到 O(n^2),适合面试和在线测评中常见的数组双指针题型。
正文完