首页 文章

在递归方法中,查找数组中最大值的索引

提问于
浏览
-2

//如 Headers 所示,我需要在int //数组中找到最大值的索引,所有这些都需要在一个方法中完成这是我的帮助器//方法到目前为止的样子

它只返回数组中的最后一个索引我可以轻松返回最大值,但我无法弄清楚如何返回该值的索引

//这是帮助方法

private int recursiveGetIndexOfLargest( int[] list, int count )
{
    int index;  
    int[] y = list;
    int temp = count - 1;
    if( count > 0 )
    {
        index = Math.max( list[list.length - 1], list[temp] );
        for(int x = 0; x < y.length; x++)
        {
            if(y[x] == index)
            {
                return x;
            }
        }
        return recursiveGetIndexOfLargest(list, temp);
    }

    else
    {
        return -1;//empty list
    }        
}

这是调用帮助器的方法

public int getIndexOfLargest()
{
    return recursiveGetIndexOfLargest(list, count);
}

3 回答

  • 1

    试试这个:

    int recursiveGetIndexOfLargest(int[] list, int count)
     {
       if (count == list.length - 1) return count;
    
       int index = recursiveGetIndexOfLargest(list, count + 1);
       return list[count] > list[index] ? count : index;
     }
    
     int[] arr = {1, 5, 2, 3, 0};
     System.out.println(recursiveGetIndexOfLargest(arr, 0));
    
  • 0
    int findLargestIndex(int[] array, int currentPos, int currentLargestIndex)
    {
      if(currentPos == array.length) 
          return currentLargestIndex;
      if(array[currentPost] > array[currentLargestIndex]
          return findLargestIndex(array,currentPos+1, currentPos);
      else
          return findLargestIndex(array,currentPos+1, currentLargestIndex);
    }
    

    它实际上是递归完成的O(n)循环 . 你这样开始:

    int result = findLargestIndex(array,0,0);
    

    这可以工作,但它会改变数组 .

    void findLargestIndex(int[] array, int currentPos)
    {
         if(currentPos == array.size()) return;
         array[0] = (array[currentPos] < array[currenPos + 1] ? currentPos + 1 : currentPos;
         findLargestIndex(int[] array, currentPos + 1);
    }
    

    最大的索引将被存储在数组[0](这会改变数组) .

    你只需启动该功能:

    findLargestIndex(array,0);
    

  • 0

    谢谢tomse !!!!!!!!

    参数count实际上是数组的大小,所以我稍微改了一下

    private int recursiveGetIndexOfLargest( int[] list, int count )
    {
        int index;
        int temp = count - 1;
        if( temp == 0 )
        {
            return temp;
        }
    
        else
        {
            index = recursiveGetIndexOfLargest(list, temp);
            return list[temp] > list[index] ? temp : index;
        }
    }
    

    现在它该死的,我浪费了几个小时的失败

相关问题