1. 题目描述
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 题解
参考官方解答,采用“排序 + 双指针”的思路,首先对数组排序,然后指针first指向a, 然后指针second从first+1开始,指针third从n-1开始,每次计算当前三数之和,如果sum > target,则指针third向左移动,否则指针second向右移动。
class Solution {
public int threeSumClosest(int[] nums, int target) {
int minRes = 10000;
int n = nums.length;
//对数组排序
Arrays.sort(nums);
for(int first = 0; first < n; first++){
if(first != 0 && nums[first] == nums[first-1]){
continue;
}
int second = first+1, third = n-1;
while(second < third){
int sum = nums[first] + nums[second] + nums[third];
if(sum == target){
return target;
}
if(Math.abs(sum - target) < Math.abs(minRes - target)){
minRes = sum;
}
//指针third左移
if(sum > target){
int temp = third - 1;
while(second < temp && nums[temp] == nums[third]){
temp--;
}
third = temp;
}else{
//指针second左移
int temp = second + 1;
while(temp < third && nums[temp] == nums[second]){
temp++;
}
second = temp;
}
}
}
return minRes;
}
}
时间复杂度:O(n*n),
空间复杂度:O(1)。