【问题标题】:Finding the max number with Divide and Conquer in Java在 Java 中使用分而治之找到最大数量
【发布时间】:2015-12-31 07:26:50
【问题描述】:

我正在尝试使用分治法(递归)来查找数组中的最大数。但是当我编译这段代码时,我得到了 ArrayIndexOutOfBounds 异常。

我不确定我哪里出错了。这是我的代码 sn-p:

public class ... {
  int[] A = {2,4,5,1,6,7,9,3};
  int max;

  public void solution() {
    max = findMax(0, A.length-1);
    //print max
  }

  private int findMax(int a, int b){    
    if(b-a == 1){
        return A[a]>A[b] ? A[a] : A[b];
    }
    else if(a==b){
        return A[a];
    }

    return findMax(findMax(a, (a+b)/2), findMax((a+b)/2 +1, b));
  }

}

【问题讨论】:

  • 哪一行?您是否尝试过使用调试器?

标签: java recursion divide-and-conquer


【解决方案1】:

问题出在你的最后一行:

return findMax(findMax(a, (a+b)/2), findMax((a+b)/2 +1, b));

这将使用findMax() 方法的结果作为另一个findMax() 调用的参数,这意味着它们将用作数组的索引。这会给你一个错误的结果或导致ArrayIndexOutOfBoundsException

您要做的是返回两个 findMax() 调用中的最大值:

return Math.max(findMax(a, (a+b)/2), findMax((a+b)/2 + 1, b));

【讨论】:

    【解决方案2】:

    我认为这不是递归的最佳用途。但是,我认为这会更容易理解。希望对你有帮助,加油!

    public static int maxI(int[] x, i index){
      if (index > 0) 
      {
        return Math.max(x[i], maxI(x, i-1))
      } 
      else 
      {
        return x[0];
      }
    }
    

    【讨论】:

    • 这不是分而治之。它按顺序查看。
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2013-01-16
    • 2017-01-12
    • 2016-06-15
    • 2017-06-07
    • 1970-01-01
    • 2017-02-17
    • 2016-05-01
    相关资源
    最近更新 更多