这题和第15题很类似,解题思路也差不多,虽然耗时蛮长的,用了三层循环,但是很快就写出来了还是很开心。
思路可以看看之前写的第15题:
第15题:三数之和博客
【题目描述】
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
【示例】
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 ≤ n u m s . l e n g t h ≤ 1 0 3 3 \le nums.length \le 10^3 3≤nums.length≤103
− 1 0 3 ≤ n u m s [ i ] ≤ 1 0 3 -10^3 \le nums[i] \le 10^3 −103≤nums[i]≤103
− 1 0 4 ≤ t a r g e t ≤ 1 0 4 -10^4 \le target \le 10^4 −104≤target≤104
【解题过程】
【思路】
和15题很相似,用双指针,排除一些重复的情况,可以通过测试。
【代码】
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());//排序
int len=nums.size();
int ans=999999;
int dis=999999;
for(int first=0;first<len;++first){
if(first>0 && nums[first]==nums[first-1]){
continue;//跳过重复的情况
}
for(int second=first+1;second<len;++second){
if(second>first+1 && nums[second]==nums[second-1]){
continue;//跳过重复情况
}
for(int third=len-1;third>second;--third){
if(third<len-1 && nums[third]==nums[third+1]){
continue;//跳过重复情况
}
int temp=nums[first]+nums[second]+nums[third];
if(abs(temp-target)<dis){
dis=abs(temp-target);
ans=temp;
}
}
}
}
return ans;
}
};
运行结果: