Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Created August 23, 2016 11:52
Show Gist options
  • Save lyleaf/dc70a8fddaaab08aa746cdb7bd3d2fd8 to your computer and use it in GitHub Desktop.
Save lyleaf/dc70a8fddaaab08aa746cdb7bd3d2fd8 to your computer and use it in GitHub Desktop.
一个vector里3个数加在一起离target最近的值。Two Pointers
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = target + 1000;
sort(nums.begin(),nums.end());
for (int i=0;i<nums.size()-2;i++){
int target2 = target - nums[i];
int j=i+1;
int k=nums.size()-1;
while (j<k){
if (abs(nums[j]+nums[k]-target2)<abs(res-target)){
res = nums[j]+nums[k]+nums[i];
}
if (nums[j]+nums[k] > target2) k--;
else if (nums[j]+nums[k] < target2) j++;
else return target;
}
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment