好吧,伙计们,我已经暂时停留在这个问题上一段时间了,而且还没能超越它。这是针对Java的。在这一点上,我感谢任何帮助。以下是详细信息:请注意,我们必须在O(n)运行时执行此操作。我们给出了一系列数字,并且必须通过它来确定是否有任何3个数字与特定数字相加。但是,我们被允许重复使用数组中的任何数字最多3次,因为我们总共需要3个数字。我们还必须输出哪3个数字给出了总和。返回真或假。
以下是我所得到的:
你们有什么建议吗?
答案 0 :(得分:0)
你可以在for循环内部的for循环中创建一个for循环。这是为学校,所以我不会给你代码,但我会给你伪。
编辑:错过了O(n)部分,对不起。这种方式应该有效。
public static void main(String[] args)
{
int[] test = {1,8,2,3,11,4};
System.out.println(threeSumTo(test, 6));
}
//check if 3 numbs in an array add up to int x
public static boolean threeSumTo(int[] array, int x)
{
//loop through the array
for (int i = 0; i < array.length; i++) {
boolean result = twoSumTo(array, x - array[i], i);
if (result) {
return result;
}
}
return false;
}
private static boolean twoSumTo(int[] array, int x, int low) {
int high = array.length - 1;
while (low < high) {
if (array[low] + array[high] == x) {
return true;
}
if (array[low] + array[high] > x) {
high--;
} else {
low++;
}
}
return false;
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
这被称为3和问题,到目前为止在O(N)中解决这个问题是不可能的。你能做的最好的是O(N ^ 2)。
检查this article。