问题描述
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.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路分析
给一个数组,找到数组中三个数的和最接近target的值。
类似于3sum的做法,转化为2sum来解决。首先将数组排序,然后循环确定一个first的值,second比first大1,third则从数组尾部开始遍历。
然后计算这三个数的和,与target比较,相等就直接返回,绝对值更小就更新,然后根据大小关系移动second或者third指针。
代码
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3)
return 0;
int cloest = nums[0] + nums[1] + nums[2];
sort(nums.begin(), nums.end());
for (int first = 0; first < nums.size() - 2; first++){
if (first > 0 && nums[first] == nums[first - 1]) continue;
//same output, pass.
int second = first + 1;
int third = nums.size() - 1;
while (second < third){
int cur = nums[first] + nums[second] + nums[third];
if (cur == target)
return cur;
if (abs(cur - target) < abs(cloest - target)){
cloest = cur;
}
if (cur < target)
second++;
else
third--;
}
}
return cloest;
}
};
时间复杂度:
O(n2)
O
(
n
2
)
空间复杂度:
O(1)
O
(
1
)
反思
sort非常重要,对于相同情况的判断可以减轻计算量。还可以计算头三个和后三个的和来快速解决一些特殊的测试用例。