【问题标题】:Return a min & max value and their positions within an arraylist using recursion使用递归返回数组列表中的最小值和最大值及其位置
【发布时间】:2019-02-01 01:09:43
【问题描述】:

我需要编写一个递归函数,返回 ArrayList 中的最大和最小元素以及相应的索引。要返回这四个项目,我需要返回一个对象,它是一个名为 MinMaxObject 的内部类的实例,它具有四个已定义的私有变量:max、min、maxPos、minPos,类型为 double、double、int 和 int。

我自己到了这里,我需要开始递归,但我不知道如何开始。如果有人能指出我正确的方向,我应该能够把它捡起来。

public static void main(String args[]) {

    Scanner console = new Scanner(System.in);
    System.out.print("Please enter a file name");
    String fileName = console.next();

    try {
        File fileRef = new File(fileName);
        Scanner tokens = new Scanner(fileRef);
        double input = tokens.nextDouble();

        ArrayList<Double> list = new ArrayList<Double>();

        while (tokens.hasNextLine()) {
            list.add(input);
        }

        System.out.println("For Loop");
        for (int counter = 0; counter < list.size(); counter++) {
            System.out.println(list.get(counter));
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


// 2 functions, one initialize & one to call the original recursion
    //can start at beggining and recurse to the end or vice versa
    //updates the min and max as it goes
    //update minPos and maxPos as well
}

public class MinMaxObject {
    private double min;
    private double max;
    private int minPos;
    private int maxPos;

public MinMaxObject(double newMin, double newMax, int newMinPos, int newMaxPos){
    min = newMin;
    max = newMax;
    minPos = newMinPos;
    maxPos = newMaxPos;
}

public double getMin(){
    return min;
}

public void setMin(double newMin){
    min = newMin;
}

public double getMax(){
    return max;
}

public void setMax(double newMax){
    max = newMax;
}

public int getMinPos(){
    return minPos;
}

public void setMinPos(int newMinPos){
    minPos = newMinPos;
}
public int getMaxPos(){
    return maxPos;
}

public void setMaxPos(int newMaxPos){
    maxPos = newMaxPos;
}

【问题讨论】:

    标签: java recursion arraylist


    【解决方案1】:

    听起来递归是作业的一部分。

    最简单的方法是遍历数组列表,但由于您需要递归,所以它有点复杂。因为这是家庭作业,而且因为我很懒,所以我不会给你可编译的 Java 代码。这是一个接近的近似值。我也不会给你整个方法,因为你应该从这里弄清楚其余的。

    private int min = 0;
    private int max = 0;
    findMinMax(int index, List<int> list)
    {
        //in recursion always start your method with a base-case
        if(index >= list.Count)
            return ;
    
        //find min and max here
    
        //this is called tail recursion, it's basically the same as a loop
        findMinMax(index + 1, list);
    }
    

    【讨论】:

      【解决方案2】:

      感谢@ScubaSteve! ...我概述了一点/详细:

      void findMinMax(int idx, List items, MinMaxObject result) {
          // this is good:
          if (idx >= items.size()) {
              return;
          }
          // check whether list[idx] is min or max: compare with & store to 'result'
      
          // recursion:
          findMinMax(idx + 1, items, result);
      }
      

      初始/最终/外部调用将是:

      // initialize with high min, low max and "out of range" indices
      // ...alternatively in default constructor/field declaration.
      MinMaxObject result = new MinMaxObject(Integer.MAX_VALUE, Integer.MIN_VALUE, -1, -1);
      // start recursion at index 0:
      findMinMax(0, items, result);
      

      一种递归替代方案是:不仅要追索列表的“头”(idx : 0 ... size - 1),还要追索“尾”,例如:

      void findMinMax(int head, int tail, List items, MinMaxObject result) {
          if(head > tail) {
              // done!
              return;
          }
          // check items[head] and items[tail]... store to result
          // iterate:
          return findMinMax(head + 1, tail - 1, items, result);
      }
      

      “替代方案”将递归计数减半(但将“内联复杂度”加倍)。


      另一种“分而治之”的方法:

      void findMinMax(int left, int right, items, result) {
          if(left > right) {
              return;// alternatively do nothing
          } else if (left == right) {
             //check items[left] ...
             // return;
          } else { // left < right
              int mid = (right - left) / 2;
              findMinMax(left, mid, items, result);
              findMinMax(mid + 1, right, items, result);
              // return;
          }
      }    
      

      ...具有(相同)O(n) 复杂性。

      【讨论】:

        【解决方案3】:

        类似这样的:

        MinMaxObject findMaxMin(final ArrayList<Double> nums, MinMaxObject minMax, int pos){
        
                //Base Case
                if(pos >= nums.size()){
                    return minMax;
                }
        
                //Check to see if the current element is bigger than max or smaller than min
                Double value = nums.get(pos); 
                if(value > minMax.getMax()){
                    //adjust minMax
        
                }
                if(value < minMax.getMin()){
                    //adjust minMax
                }
        
                //recursion
                return findMaxMin(nums, minMax, pos+1);
        
        
            }
        

        只需确保使用适当的值初始化您的MinMaxObject(可能应该使这些部分成为默认构造函数),例如: MinMaxObject minMax = new MinMaxObject(Integer.MAX_VALUE, Integer.MIN_VALUE, -1, -1);

        希望我得到了正确的参数顺序。

        搜索“递归”和“累加器”这两个词可能会对您有所了解。

        【讨论】:

          【解决方案4】:

          递归是不必要的。使用ArrayList List,这是一个示例。

          Collections.sort(List)
          return List.get(0); // Least number
          return List.get(List.size()-1); // Max number
          

          【讨论】:

            【解决方案5】:
            public void getMinMax(MinMaxObject minMaxObject, List list, int currentIndex)
            {
            
            if(list.get(currentIndex) < minMaxObject.getMin())
            
                minMaxObject.setMin(list.get(currentIndex) );
                minMaxObject.setMinPos(currentIndex) ;
            
            else if(list.get(currentIndex) > minMaxObject.getMax())
            
                minMaxObject.setMax(list.get(currentIndex));
                minMaxObject.setMaxPos(currentIndex) ;
            
            if(currentIndex < list.size-1) getMinMax(minMaxObject, list, ++currentIndex)
            
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-03-05
              • 1970-01-01
              • 2016-02-24
              • 2016-05-07
              • 2020-07-07
              • 2021-07-09
              • 1970-01-01
              • 2021-08-07
              相关资源
              最近更新 更多