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

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;
}
上一篇:python爬虫:搜狗微信公众号文章信息的采集(https://weixin.sogou.com/),保存csv文件


下一篇:Linux 环境 Intelij Idea 安装与快捷图标配置