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 len = nums.size(), res = 0, diff = INT_MAX; | |
if (len < 3)return diff; | |
sort(nums.begin(), nums.end()); | |
for (int i = 0; i + 2 < len; ++i) | |
{ | |
int lo = i + 1, hi = len - 1; | |
while (lo < hi) | |
{ | |
int sum = nums[i] + nums[lo] + nums[hi]; | |
if (sum == target)return target; | |
else | |
{ | |
if (abs(sum - target) < diff) | |
{ | |
diff = abs(sum - target); | |
res = sum; | |
} | |
if (sum < target)++lo; | |
else --hi; | |
} | |
} | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment