Skip to content

Instantly share code, notes, and snippets.

Created August 23, 2016 11:52
What would you like to do?
一个vector里3个数加在一起离target最近的值。Two Pointers
class Solution {
int threeSumClosest(vector<int>& nums, int target) {
int res = target + 1000;
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