这个还是用到了以前的一个技巧,先排序,然后从两头往中间找最合适的数。不过是多了一层循环,先选定一个数,然后再去试另外两个数。
public class Solution {
public int threeSumClosest(int[] num, int target) {
List<Integer> sortedNum = new ArrayList<Integer>();
for (int i = 0; i < num.length; ++i) {
sortedNum.add(num[i]);
}
Collections.sort(sortedNum);
int closest = num[0] + num[1] + num[2];
int min = Math.abs(closest - target);
for (int i = 0; i < num.length - 2; ++i) {
int num1 = sortedNum.get(i);
for (int j = i + 1, k = (num.length - 1); j < k;) {
int temp = num1 + sortedNum.get(j) + sortedNum.get(k);
if (temp > target) {
--k;
} else {
++j;
}
if (Math.abs(temp - target) < min) {
min = Math.abs(temp - target);
closest = temp;
}
}
}
return closest;
}
}
本文介绍了一种通过排序与循环优化解决三数之和问题的方法,包括如何选择中间数值并进行试错,以达到目标值。详细阐述了算法实现步骤及效率提升策略。

2022

被折叠的 条评论
为什么被折叠?



