public class SumOfTwoNum {
public int[] twoSum(int[] numbers, int target) {
int med = numbers.length/2;
if (numbers[med] > target) {
twoSum(Arrays.copyOfRange(numbers,0,med), target);
}
int remainNum;
int index1 = -1;
int index2 = -1;
while (index1 == -1 && index2 == -1) {
remainNum = target-numbers[med];
if (remainNum > numbers[med]) {
index2 = Arrays.binarySearch(numbers,med,numbers.length,remainNum);
index1 = med;
} else {
index1 = Arrays.binarySearch(numbers,0,med,remainNum);
index2 = med;
}
//here I get index1=0 and index2=1, but the loop doesn't stop
med --;
}
return new int[] {index1, index2};
}
public static void main(String[] args) {
SumOfTwoNum s = new SumOfTwoNum();
System.out.println(Arrays.toString(s.twoSum(new int[] {2,7,11,15},9)));
//what I hope to get here is {0,1}, but it returns {-1,2}
}
}
我想获取两个数字的索引,这些索引加起来等于目标 但是当它进入循环时,即使index1和index2都不为-1,它仍然保持循环
答案 0 :(得分:0)
问题是在递归调用之后,您的函数没有返回,因此循环执行两次。因此,即使条件变为假,循环似乎仍在执行。
您需要返回递归调用的结果。
if (numbers[med] > target) {
return twoSum(Arrays.copyOfRange(numbers,0,med), target);
}