问题描述
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
解题思路
- Brute force 生成所有三元组,然后判断和是否是最接近的值
- 排序扩展法, 先排序,确定一个元素之后,确定后面两个元素来判断能否更新最接近的值。由于先排序了,可以用头尾指针线性的过一遍就可以。这题不需要判断是否重复,所以直接判断即可。
代码实现
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = Integer.MAX_VALUE - nums[nums.length - 1];
for(int i = 0; i < nums.length - 2; i++) {
int start = i + 1, end = nums.length - 1, sum = target - nums[i];
while(start < end) {
int tmp = nums[start] + nums[end];
//判断能否更新sum的情况
if(Math.abs(tmp - sum) < Math.abs(res-target)) res = tmp + nums[i];
if(tmp > sum) {
while(end >= 1 && nums[end] == nums[end - 1]) end--;
end--;
} else if(tmp < sum) {
while(start < nums.length - 1 && nums[start] == nums[start + 1]) start++;
start++;
} else {
return target;
}
}
}
return res;
}
复杂度分析
对于实现1的brute force方法,时间复杂度是O(n3)(这里直接判断即可,三层循环里面是O(1)的时间),空间复杂度是O(1)
对于实现2的方法, 时间复杂度是O(n2), 空间复杂度是O(1)
分析
这题跟上一题很相似,实现方法也很类似。