【问题标题】:Finding the max value in an ArrayList of integers using recursion使用递归在整数的 ArrayList 中查找最大值
【发布时间】:2020-03-31 22:30:13
【问题描述】:

我对此没有太多了解...我的任务是创建一个递归方法,该方法将输出整数 ArrayList 中的最大值。

public static int maxValue(ArrayList<Integer> a)
    {
        if (a.isEmpty()) throw new NoSuchElementException ("Can't compute max of empty list.");
        if(a.size()==1){return a.get(0);}
        else {
            //not sure what to add here for the recursion
        }
    }

【问题讨论】:

    标签: java recursion arraylist


    【解决方案1】:

    执行此操作的方法实际上是比较前两个值并删除最小的一个(或其中一个,如果相等)并设置列表大小为 1 的基本情况,如下所示:

    public static int maxValue(ArrayList<Integer> a)
        {
            if (a.isEmpty()) return -1;
            if (a.size() == 1) return a.get(0);
            if (a.get(0) <= a.get(1))
            {
                a.remove(0);
            } else
            {
                a.remove(1);
            }
            return maxValue(a);
        }
    

    【讨论】:

    • 解决方案很糟糕,因为它破坏了输入。至少,它应该使用输入的副本,尽管这会使其速度变慢且占用内存。
    • 是的,我想提一下,但根据 OP 写的内容(起始代码),这就是作业需要的内容
    【解决方案2】:

    试试这个:

    import java.util.List;
    import static java.util.Math.*;
    import java.util.NoSuchElementException;
    import static java.util.Objects.*;
    
    public static int maxValue( List<Integer> list )
    {
        if( isNull( list ) ) throw new IllegalArgumentException( "list is null." );
        if( list.isEmpty() ) throw new NoSuchElementException( "Can't compute max of empty list." );
    
        var size = list.size();
        var head = list.get( 0 );
        var retValue = size == 1 ? head : max( head, maxValue( list.sublist( 1, size ) ); 
        return retValue;
    }
    

    List.subList() 不返回(子)列表的副本,而是返回底层列表的新视图。

    【讨论】:

      【解决方案3】:

      如果要求允许,可以添加第二个参数 n,并传递 ArrayList 的大小。

         ...
         System.out.println(maxValue(arrlst, arrlst.size()));
         ...
      
      
      public static int maxValue(ArrayList<Integer> a, int n) {
          if (n == 1)
              return a.get(0);
      
          return Math.max(a.get(n - 1), maxValue(a, n - 1));
      }
      

      【讨论】:

        猜你喜欢
        • 2013-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        • 1970-01-01
        • 2023-04-07
        • 2016-05-07
        • 1970-01-01
        相关资源
        最近更新 更多