【问题标题】:How to find the location of the largest element in an array using recursion?如何使用递归找到数组中最大元素的位置?
【发布时间】:2014-04-11 00:38:57
【问题描述】:

给定一个数组列表,列表中元素的计数使用递归找到最大元素的位置。

到目前为止,我能够找到最大的元素,但我需要该元素在数组中的位置,而不是实际值。

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;
} 

【问题讨论】:

  • 递归解决方案是愚蠢的。你有一个值数组;遍历列表一次,您将获得最大值。如果这是学校作业,请考虑在说明中加入“请解决我的家庭作业”。
  • 用递归解决这个问题真是太愚蠢了,但可以训练你的递归知道如何。
  • @AlexWien:你去年 10 月解决了这个问题没那么愚蠢 :) stackoverflow.com/a/19590979/2591612
  • 我们将在 SO 上遇到愚蠢的递归问题,因为课堂老师似乎认为对所有事情都使用递归很酷。

标签: java


【解决方案1】:

您在正确的轨道上,但您只需要一些调整。我不会为你写代码,但这里有一些线索。

如果您希望您的函数返回索引而不是最大值,那么您需要更改计算返回值的方式递归使用它的方式。

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 和其他索引,并且您想要计算较大值的 indexMath.max 无法做到这一点,但您可以使用 if 语句或条件运算符 a ? b : c。重命名变量也很有帮助,因为它不再包含最大值。

【讨论】:

  • 感谢您的评论 ajb。我最初试图使用 if 语句而不是 Math.max,但我不明白的部分是如果我使用 if 语句,我将如何指示与 list[count-1] 比较的内容。如果 list[count-1] > something[?]{return count-1} 否则返回 {?]。我真的不希望你给我答案,如果你能像以前一样用线索解释的话。谢谢
  • 我更改为 Math.max 的原因是因为如果我找到最大值,我可以搜索找到该值的数组以获取索引。然而这并没有奏效。
  • @user3282395 “某事”是list[n],其中n 是其他一些索引。这就是我要说的全部内容,但是您应该能够通过重新阅读我的答案来弄清楚其他索引是什么。
  • 再次感谢 ajb,我一遍又一遍地重新阅读您的信息,并且能够让它发挥作用。
【解决方案2】:

一个想法可能是将您的数组 recursiv 拆分为两部分,直到只剩下 2 或 1 个元素。在两个数字或一个数字中找到最大值很简单并返回它。然后你比较两个返回值并返回最大值。

【讨论】:

  • 所以是二分查找,但要找最大的数? :)
  • 您没有阅读问题。他已经有返回最大值的代码(但可能存在错误)。
【解决方案3】:

递归很简单,但你应该知道如何迭代:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2011-12-29
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多