我正在学习递归,我只是不明白为什么这个方法不能正常工作。
public static boolean theSame(int[] arr, int start, int end) {
if(arr[start]==arr[end]) {
if(start!=end) {
start++;
theSame(arr, start, end);
}
else {
return true;
}
}
return false;
}
数组是 4, 4, 4, 4, 4, 4
我正在从索引 1 和 5 测试它。结果是什么?为什么它不起作用?我假设这与我的 if(start!=end)
条件有关,但我不确定。
我忘了补充一点,该方法在应该明确返回 true 时返回 false。
最佳答案
public static boolean theSame(int[] arr, int start, int end) {
if(arr[start]==arr[end]) {
if(start!=end) {
start++;
theSame(arr, start, end); // here's your problem
// return theSame(arr, start, end); might work better
}
else {
return true;
}
}
return false;
}
不过,您可以在一行中完成。
public static boolean theSame( int[] arr, int start, int end ) {
return start >= end || (
arr[ start ] == arr[ end ] && theSame( arr, start + 1, end )
);
}
关于java - 用于测试数组元素是否与某些索引相等的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054233/