【发布时间】:2014-02-12 21:37:08
【问题描述】:
好的,谢谢大家的帮助!特别感谢@pjs 让我知道如何去做。这是我的新代码,但由于某种原因,它不会达到基本情况之一。抱歉,如果我删除了旧代码,这是我第一次在这里发布,我不确定是否应该用新代码回答我自己的问题。
//initialized int start = 0
//initialized int end = length of the array
//here goes the constructor
public boolean kPairSum(Integer k) {
if (sortedIntegerArray.length < 2) { //if array is less than two return false
return false;
}
else if (start == end) { //once the start and the end meets. This is the base case that doesn't seem to work for me.
return false;
}
else {
int currentStart = sortedIntegerArray[start]; //get first int in the array
int currentEnd = sortedIntegerArray[end-1]; //get the very last int in the array
int sum = currentStart + currentEnd; //get the sum
if (k.equals(sum)) { //compare sum and k if equal
return true;
}
else if (sum <k) { //if sum is less than k then increment value of start
start++;
return kPairSum(k);
}
else if (sum > k) { //if sum is greater than k then it decrements value of end
end--;
return kPairSum(k);
}
else { //not sure if this is right, should I just get rid of the else if statement for sum > k and change it to just an else? I wrote this down cause it has to return a type of boolean.
return kPairSum(k);
}
}
【问题讨论】:
-
您“检查数组中每个可能的对”的方法不是 O(n) - 有 O(n^2) 个这样的对。 O(n)(平均情况)解决方案需要 O(n) 额外空间,使用哈希表
-
乍一看,由于 if/else 语句,它永远不会调用您的递归函数 return kPairSum(k)。
-
@jrowe08 是的,我有一个不同的代码,它在 else 语句中进行了递归调用,但它一直给我一个 stackoverflow 错误,我认为这是因为我的基本情况无法访问所以我放弃了最后写了这样的代码:(
-
@user3303632 它永远不会调用 kPairSum 并且永远不会像现在的代码那样增加您的 x 变量
-
没关系,我知道了,当我将 end 设置为长度时,我也立即减去了 1。因此,我只是将变量 end 放入 currentEnd 而不是 end-1。谢谢大家!