题目
16. 最接近的三数之和
题解
一、双指针思想
1 首先进行数组排序,时间复杂度,然后设置一个
dis = Integer.MAX_VALUE
2 在 nums 数组进行遍历,每遍历一个元素,利用该元素的下标i,得到一个固定值 nums[i]
3 在创建一个前指针 start = i + 1, 再创建一个后指针 end = nums.length - 1,就是数组最后一个元素的下标
4 然后再根据tempSum = nums[i] + nums[start] + nums[end],然后进行比较用tempSum和目标值相减的绝对值来和dis比较大小。
5 如果dis大于绝对值那么,就是就可以更新ans了,把ans = tempSum
6 如果tempSum > target,那么就 end--
7 如果 tempSum < target,那么就 start++
整个遍历过程,固定值为 n 次,双指针为 n 次,时间复杂度为
时间复杂度:
空间复杂度:
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ans = 0;
int len = nums.length;
int dis = Integer.MAX_VALUE;
for (int i = 0; i <= len - 3; i++) {
int start = i + 1;
int end = len - 1;
while (start < end) {
int tempSum = nums[start] + nums[end] + nums[i];
if (Math.abs(target - tempSum) < dis) {
ans = tempSum;
dis = Math.abs(target - tempSum);
}
if (tempSum < target) {
start++;
} else if (tempSum > target) {
end--;
} else {
return target;
}
}
}
return ans;
}