Created
August 23, 2016 11:52
-
-
Save lyleaf/dc70a8fddaaab08aa746cdb7bd3d2fd8 to your computer and use it in GitHub Desktop.
一个vector里3个数加在一起离target最近的值。Two Pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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