Description:
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).
解题思路:
题意是让我们在一个给定数组中S(假设这里数组S的长度为len),从len个元素任取3个元素,返回(满足:这3个元素之和与target最接近)的和。此题与LeetCode 解题报告 015. 3Sum 思路很类似,只不过在这样需要注意的是如果一开始3个元素的之和是大于INT_MAX会导致求和之后为负数,所有这里保存3个元素的之和为数据类型为long。
算法思路:
- 步骤1 首先对数组nums进行排序(按照从小到大);
- 步骤2 依次考虑第一个元素选取为 nums[0], nums[1], ... , nums[num.size()-3]时的情况:
-
- 当第一个元素选取nums[i],第二个元素和第三个元素选取范围在nums[i] ~ nums[nums.size()-1] 中。分别取left=i+1,right = nums.size()-1;
- 计算此时三个元素和 sum = nums[i] + nums[left] + nums[right]:
-
- 如果sum == target,则程序结束,因为这个已经是最好的情况了,return target;
- 如果sum > target,则end --;
- 如果sum < target,则start ++;
- 判断此时是否abs(sum-target) < abs(res-target),那决定res的更新。
-
- 返回结果,需要注意将long类型的res变量强制转换成int类型.
-
代码如下:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { long res = INT_MAX; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i ++) { int left = i+1, right = nums.size()-1; while(left < right) { int sum = nums[i] + nums[left] + nums[right]; if(sum == target) return target; else if(sum > target) right --; else left ++; if(abs(sum-target) < abs(res-target)) res = sum; } } return (int)res; } };