16. 3Sum Closest

来源:互联网 发布:乐视自行车软件 编辑:程序博客网 时间:2024/06/05 07:44

问题:

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

分析:首先可以对数组进行排序,其次计算离目标最近的三个数之和

该算法可以分两种情况:1、当target比数组的最小的数还小,排序后的数组中最小的三个数的和为最靠近target的和

     2、其他情况下需要遍历找最靠近target的三个数的和。


代码:int threeSumClosest(vector<int>& nums, int target) {
int closestNum,sum;
sort(nums.begin(), nums.end());//数组排序
if (nums.size() < 3)//数组少于3个时返回0
return 0;
closestNum = nums[0] + nums[1] + nums[2];
if (target <= nums[0])//第一种情况
return closestNum;
for (int i = 0; i < nums.size() - 2; i++) {
int j = i + 1;
int k = nums.size - 1;
while (j < k) {
sum = nums[i] + nums[j] + nums[k];
if (abs(target - closestNum) > abs(target - sum)) {//当前单个数和李target更近时,令该和为最靠近target的和
closestNum = sum;
if (closestNum == target) return closestNum;
}
(sum > target) ? k-- : j++;
}
}
return closestNum;
};

0 0