地址:https://leetcode-cn.com/problems/3sum-closest/
思路:一:先排序,再遍历前二个数,在通过二分查找第三个数
二:先排序,再遍历中间数,利用两指针从数组两端开始扫描
Code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
/*
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int n=nums.size(),res=nums[0]+nums[1]+nums[2],Min=abs(res-target);
int k,xi,p;
for(int i=0;i<n-2;++i)
{
for(int j=i+1;j<n-1;++j)
{
if(nums[i]+nums[j]*2-target>Min) break;
xi=target-nums[i]-nums[j];
k=lower_bound(nums.begin()+j+1,nums.end(),xi)-nums.begin();
if(k&&k-1!=j&&abs(xi-nums[k-1])<Min){
res=nums[i]+nums[j]+nums[k-1];
Min=abs(xi-nums[k-1]);
}
if(k<n&&abs(xi-nums[k])<Min){
res=nums[i]+nums[j]+nums[k];
Min=abs(xi-nums[k]);
}
}
}
return res;
}
};
*/
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int n=nums.size(),res=nums[0]+nums[1]+nums[2],Min=abs(res-target);
int l,r,p;
for(int i=1;i<n-1&&Min;++i)
{
l=0; r=n-1;
while(l<i&&r>i){
p=target-nums[l]-nums[i]-nums[r];
if(p>0){
if(p<Min){
res=nums[l]+nums[i]+nums[r];
Min=p;
}
++l;
}else if(p<0){
if(-p<Min){
res=nums[l]+nums[i]+nums[r];
Min=-p;
}
--r;
}else{
res=target; Min=0;
break;
}
}
}
return res;
}
};
int main()
{
int n,m,x;
vector<int> iv;
Solution So;
cin>>n>>m;
for(int i=0;i<n;++i)
{
cin>>x;
iv.push_back(x);
}
cout<<So.threeSumClosest(iv,m)<<endl;
return 0;
}