链接:https://oj.leetcode.com/problems/3sum-closest/
跟3-sum的思路是一样的。根据sum与target的大小关系,分别移动数组两端的“指针”,同时记录sum与target最小的距离
class Solution { public: int threeSumClosest(vector<int> &num,int target) { sort(num.begin(),num.end()); int sum; int d=-1; int l=1,r=num.size()-1; for(int i=0;i<num.size()-2;i++) { l=i+1; r=num.size()-1; while(l<r) { int t=num[i]+num[l]+num[r]; int c=C(t,target); if(t>target) r--; else l++; if(c<d||d==-1) { sum=t; d=c; } } } return sum; } int C(int t,int target) { return target>t?target-t:t-target; } };