【发布时间】:2012-07-27 04:40:44
【问题描述】:
这是我被要求解决的一个面试问题:给定一个未排序的数组,找出数组中的 2 个数字及其总和。 (也就是说,在数组中找到三个数字,其中一个是另外两个的总和。)请注意,我已经看到了关于在给定总和 (int k) 时找到 2 个数字的问题。但是,这个问题希望您找出数组中的数字和总和。是否可以在 O(n)、O(log n) 或 O(nlogn) 中求解
有一个标准的解决方案是遍历每个整数,然后对其进行二进制搜索。有没有更好的解决方案?
public static void findNumsAndSum(int[] l) {
// sort the array
if (l == null || l.length < 2) {
return;
}
BinarySearch bs = new BinarySearch();
for (int i = 0; i < l.length; i++) {
for (int j = 1; j < l.length; j++) {
int sum = l[i] + l[j];
if (l[l.length - 1] < sum) {
continue;
}
if (bs.binarySearch(l, sum, j + 1, l.length)) {
System.out.println("Found the sum: " + l[i] + "+" + l[j]
+ "=" + sum);
}
}
}
}
【问题讨论】:
-
如果没有给出
k,那么……任务是什么?我不明白...你能举个例子吗(输入+预期输出)? -
任务是在数组中找到三个数字,使得三个数字中的一个是另外两个的和。
标签: algorithm