two pointers O(n^2)
public class Solution {
public int threeSumClosest(int[] num, int target) {
if (num == null || num.length <= 2) return 0;
Arrays.sort(num);
int closest = num[0] + num[1] + num[2];
for (int i = 0; i < num.length; i++) {
int p = i+1;
int q = num.length - 1;
while (p < q) {
int temp = num[i] + num[p] + num[q];
if (temp == target) {
return target;
}
if (temp < target) {
p++;
} else {
q--;
}
closest = Math.abs(temp - target) < Math.abs(closest - target) ? temp : closest;
}
}
return closest;
}
}

本文介绍了一个解决三数之和最接近给定目标值问题的算法实现。通过先排序再使用双指针技巧遍历数组,找到与目标值差距最小的三个数之和。该算法的时间复杂度为O(n^2)。
1172

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



