给定一个数组列表,列表上的元素计数使用递归查找最大元素的位置。
到目前为止,我能够找到最大的元素,但是我需要该元素在数组中的位置,而不是实际值。
private int getLargestElementLoca(int[] list, int count)
{
int largestValue;
if(count == 1){
return 0;
}
int tempMax = getLargestElementLoca(list,count-1);
largestValue = Math.max(list[count-1],tempMax);
return largestValue;
} 发布于 2014-04-10 16:38:57
你在正确的轨道上,但你只是需要一些调整。我不会给你写代码,但这里有一些线索。
如果希望函数返回索引而不是最大值,则需要更改计算返回值的方式和递归使用它的方式。
private int getLargestElementLoca(int[] list, int count)
{
int largestValue;
if(count == 1){
return 0;
}如果只需要查看一个元素,即list[0],那么list[0]将是最大值,0将是它的索引。所以返回0是正确的。
int tempMax = getLargestElementLoca(list,count-1);您已经重新定义了getLargestElementLoca,以便它返回索引,而不是最大值。这也适用于递归调用,因此tempMax将是一个索引,而不是一个值。这意味着您不能将它直接传递到Math.max。有些调整是必要的,但要继续阅读。
largestValue = Math.max(list[count-1],tempMax);Math.max返回最大的值,但这不是您想要的。您有两个索引,count-1和其他什么,您想要计算较大值的索引。您不能在Math.max中这样做,但是可以使用if语句或条件运算符a ? b : c。重新命名变量也很有帮助,因为它将不再包含最大的值。
发布于 2014-04-10 16:32:35
一种方法是将数组递归分解为两个部分,直到只剩下2或1个元素。在两个数字或一个数字中找到最大值是简单的,并返回它。然后比较这两个返回的值并返回最大值。
发布于 2014-04-10 16:32:45
递归很简单,但是您应该知道如何迭代地这样做:
private int getMaxLocation(int[] array) {
int maxpos = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
maxpos = i;
}
}
return maxpos;
}如果要通过递归进行此操作,则需要跟踪其中的几个变量:
private int getMaxLocation(int[] array, int pos, int max, int maxpos) {
if (pos >= array.length || pos < 0) {
return maxpos;
} else {
int current = array[pos];
if (current > max) {
max = current;
maxpos = pos;
}
return getMaxLocation(array, ++pos, max, maxpos);
}
}
//calling this
int max = getMaxLocation(yourArray, 0, Integer.MIN_VALUE, 0);https://stackoverflow.com/questions/22993668
复制相似问题