题目:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int res = nums[0] + nums[1] + nums[2];//获取和最小值
for(int ind = 0 ; ind < nums.size()-2; ind++){
int mid = ind + 1 , lar = nums.size()-1;
while(mid < lar){
int sum = nums[ind] + nums[mid] + nums[lar];
if(target == sum) return sum;
if(abs(target - sum) < abs(target - res)) res = sum;
else if(sum < target) mid++;
else lar--;
}
return res;
}
mid 和 lar 双指针遍历!