题目描述(Medium)
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
题目链接
https://leetcode.com/problems/3sum-closest/description/
Example 1:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
算法分析
先排序,然后左右夹逼,复杂度
。
提交代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int min_gap = INT_MAX;
int result;
for (auto i = nums.cbegin(); i < nums.cend() - 2; ++i)
{
auto j = i + 1, k = nums.cend() - 1;
while (j < k)
{
if (abs(*i + *j + *k - target) < min_gap)
{
min_gap = abs(*i + *j + *k - target);
result = *i + *j + *k;
}
if ((*i + *j + *k) < target)
++j;
else if ((*i + *j + *k) > target)
--k;
else
return target;
}
}
return result;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int target, int expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
int result = s.threeSumClosest(nums, target);
if (result == expected)
printf("passed\n");
else
printf("failed\n");
}
int main(int argc, char* argv[])
{
vector<int> array1 = { -1, 2, 1, -4 };
Test("Test1", array1, 1, 2);
return 0;
}