3Sum Closest

来源:互联网 发布:人工智能三贤者理论 编辑:程序博客网 时间:2024/06/06 03:47

1.问题描述

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).

2.解题思路

这道题目和3Sum的题目基本一致,解题方法也大体相同,只是需要注意一些细节即可。3Sum的具体解决方法参见我的另一篇文章THREE SUM。

首先将原数组进行排序,得到有序数组,然后建立一个从头遍历到结尾的循环,在此循环过程中,从第二个位置和最后一个位置开始夹逼,求出这三个数的和tmpSum,每次求tmpSum与target求差tmpMin,如果abs(tmpMin)小于初试的最小值min,则对min进行更新,知道遍历结束,rslt中保存了最接近的和,min中保存了最小差的绝对值,最后返回。整个过程算法复杂度为O(n^2)

3.代码实现:

class Solution {public://该函数返回一个数的绝对值template<typename T>T abs(const T t){if (t >= 0)return t;elsereturn -t;}//返回最近接的和int threeSumClosest(std::vector<int>& nums, int target) {if (nums.size() < 3)return 0;//排序sort(nums.begin(), nums.end());int rslt = nums.at(0)+ nums.at(1)+nums.at(2);auto it1 = nums.begin();//min保存最小值int min = abs(rslt - target);while (it1 != nums.end() - 1){auto it2 = it1 + 1;auto it3 = nums.end() - 1;while (it2 < it3){int tmpSum = *it1 + *it2 + *it3;int tmpMin = tmpSum - target;if (tmpSum < target)++it2;else if (tmpSum == target)return target;else--it3;//判断是否更新if (abs(tmpMin) < min){min = abs(tmpMin);rslt = tmpSum;}}++it1;}return rslt;}};
4.总结

如果不会这个问题的话,可以仔细看看我上篇文章对于3Sum问题的求解过程,而3Sum的求解过程又来自于2Sum,解决了2Sum的问题,就可以解决3Sum的问题了。


0 0
原创粉丝点击