一、题目描述
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:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
二、思路
1.首先初始化一个值
2.然后从小到大排序,并遍历容器
3.i从0到nums.size() - 2,并设两个指针,一个指向i+1,另一个指向nums.size()-1
4.这里可不考虑跳过重复的数
三、C++代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int closest = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2; i++) {
int l = i + 1, r = nums.size() - 1;
while(l < r) {
int sum = nums[i] + nums[l] + nums[r];
if(sum == target) return sum;
if(abs(target - sum) < abs(target - closest))
closest = sum;
if(sum > target) r--;
else l++;
}
}
return closest;
}
};