问题描述
问题分析
分析题目,和上一个题目相似。我就简述一下思路:将数组排好序,固定第一个数,在另外两个指针的对撞过程中,如果三数之和距离target更近了,则更新;移动第一个数,重复上述过程。
解法:对撞指针
- 时间复杂度:O( n2 ),其中n表示数组的长度。
Java代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
List<Integer> results = new ArrayList<>();
int instence = Integer.MAX_VALUE;
int result = 0;
Arrays.sort(nums);
for (int first = 0; (nums.length >= 3) && (first < nums.length-2); first++) {
//与前一个first所对的数字不重复
if (!(first > 0 && nums[first] == nums[first-1])){
int i = first + 1;
int j = nums.length - 1;
int now_result;
int now_instence;
while (i < j){//Math.abs(nums[i] + nums[j] + nums[first] - target) < Math.abs(instence)
now_result = nums[i] + nums[j] + nums[first];
now_instence = target - now_result;
if (Math.abs(now_instence) < Math.abs(instence)){
instence = now_instence;
result = now_result;
}
if (now_instence == 0){
return result;
} else if (now_instence < 0){
//在target的右边,得变小
do {
j--;
}while (j < nums.length-1 && i < j && nums[j] == nums[j+1]);
} else {
//在target的左边,得变大
do {
i++;
}while (i > 0 && i < j && nums[i] == nums[i-1]);
}
}
}
}
return result;
}
}
结果分析
以上代码的执行结果:
执行时间 | 内存消耗 |
---|---|
19ms | 35.7MB |