16. 3Sum Closest

 

Description:

https://leetcode.com/problems/3sum-closest/#/description

Algirithm:

One for loop and squeeze from left and right. This is similar to the solution of ThreeSum.

Code: (6ms, the fastest 🙂 )

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() == 3)
return nums[0] + nums[1] + nums[2];

sort(nums.begin(), nums.end());
int result = 10000;
int result_tmp = 10000;
for (int i = 0; i < nums.size() – 2; i++)
{
int left = i + 1;
int right = nums.size() – 1;
while (left < right)
{
int tmp = nums[i] + nums[left] + nums[right] – target;
result_tmp = (abs(result_tmp) < abs(tmp)) ? result_tmp : tmp;
if (tmp < 0)
left++;
else if (tmp > 0)
right–;
else
return target;
}
}
return result_tmp + target;
}
};

Leave a Reply

Your email address will not be published. Required fields are marked *