这个还是用到了以前的一个技巧,先排序,然后从两头往中间找最合适的数。不过是多了一层循环,先选定一个数,然后再去试另外两个数。
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;
}
}