如何在JAVA中检查添加到特定值的3个数字的数组?

时间:2014-09-20 20:43:30

标签: java arrays algorithm

好吧,伙计们,我已经暂时停留在这个问题上一段时间了,而且还没能超越它。这是针对Java的。在这一点上,我感谢任何帮助。以下是详细信息:请注意,我们必须在O(n)运行时执行此操作。我们给出了一系列数字,并且必须通过它来确定是否有任何3个数字与特定数字相加。但是,我们被允许重复使用数组中的任何数字最多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)

这似乎是3SUM problem的变体,应该遵守相同的限制。

在小于O(n ^ 2)的情况下计算3SUM问题仍然是一个未解决的问题。

您的老师是否提出了一个技巧问题或是某种竞争?

答案 2 :(得分:0)

这被称为3和问题,到目前为止在O(N)中解决这个问题是不可能的。你能做的最好的是O(N ^ 2)。

检查this article