LeetCode 16. 3Sum Closest
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
实现思路:
找到三个数的和使其最接近目标数,和15题一样同属于双指针题,不详细赘述了。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int minGap=0x3fffffff,res;
sort(nums.begin(),nums.end());
for(int i=0; i<nums.size(); i++) {
if(i>0&&nums[i]==nums[i-1]) continue;
int j=i+1,k=nums.size()-1;
while(j<k) {
int ansVal=(nums[i]+nums[j]+nums[k]);
if(abs(ansVal-target)<minGap) {
minGap=abs(ansVal-target);
res=ansVal;
}
if(ansVal<target) j++;//总和小于目标数的时候说明 可以让j++缩短差距
else k--;
}
}
return res;
}
};