【发布时间】:2021-03-14 15:18:01
【问题描述】:
给定一组n 不同的数字,这些数字从索引0 严格增加到m,并从索引m 严格减少到索引n-1,我想使用递归来找到索引@数组中最大数的 987654328@。我的方法需要按比例运行O(log n)
到目前为止,我一直在考虑使用二进制搜索递归算法,它确实会在我相信的给定时间复杂度下运行,并提出了以下内容;
/*
* @param inputArr -> input array of numbers over which the reccursive method is called
* @param head -> the first index of the array passed as argument
* @param tail -> the last index of the array passed as argument
* @returns max -> index for the maximum of the ascending sequence
*/
public static int largestNumber(int[] inputArr, int head, int tail) {
//base cases for recursion to stop
if(head==tail)
return head;
int midIndex = (tail + head)/2;
// the maximum is at the mid index
if(inputArr[midIndex] > inputArr[midIndex +1] && inputArr[midIndex] < inputArr[midIndex -1]) {
return midIndex;
} else {
// the maximum is not at the mid index
if (inputArr[midIndex+1] > inputArr[midIndex]) {
return largestNumber(inputArr, midIndex+1, tail);
} else {
return largestNumber(inputArr, head, midIndex - 1);
}
}
这个的输出是
这些都是不正确的(从上到下应该是0 , 3, 2, 4),表明我对基本情况或条件语句的处理不当。有人对我可能出错的地方或我遗漏了什么情况有任何暗示吗?在我看来,我的功能似乎已经完成了......
【问题讨论】:
标签: java recursion binary-search