[LeetCode] 16. 3Sum Closest 解题思路

时间:2022-03-07 11:00:17

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

问题:给定一个数组和一个整数 n ,求数组中的三个元素,他们的和离 n 最近。

这道题和 3Sum 很相似,解题思路也很相似,先排序,然后采用双指针法依次比较。

由于 3Sum 很相似,思路就不详说。主要说下不同点:

  1. 由于是求最接近值,当 s[i] + s[l] + s[r] - target == 0 的时候,即可返回结果。
  2. 返回的结果是最接近 n 的三个元素之和。
 int threeSumClosest(vector<int>& nums, int target) {

     std::sort(nums.begin(), nums.end());

     int closest = target - nums[] - nums[] - nums[];

     for (int i =  ; i < nums.size(); i++) {

         int l = i + ;
int r = (int)nums.size() - ; int newTarget = target - nums[i]; while (l < r) {
if (nums[l] + nums[r] == newTarget) {
return target;
} int diff = newTarget - nums[l] - nums[r];
if (abs(diff) < abs(closest)) {
closest = diff;
} if (nums[l] + nums[r] < newTarget){
l++;
}else{
r--;
}
}
} return target - closest;
}