您的位置:首页 > 其它

[LeetCode] 3Sum Closest

2014-04-27 17:15 357 查看
这个还是用到了以前的一个技巧,先排序,然后从两头往中间找最合适的数。不过是多了一层循环,先选定一个数,然后再去试另外两个数。

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: