【问题标题】:Finding the max value in an array, however being less than the first number in the array查找数组中的最大值,但小于数组中的第一个数字
【发布时间】:2017-03-30 18:38:57
【问题描述】:

我需要找出如何在数组中找到最大值,小于数组的第一个索引。到目前为止,我只知道如何在我的数组中找到最大值(如下所示),但我只需要帮助从我的方法返回小于数组中第一个数字的最大值。

public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}

}

【问题讨论】:

  • 提示:换句话说,所有大于或等于第一个的数字都不算数,就好像它们不存在一样。

标签: java arrays recursion


【解决方案1】:

似乎递归方法太过分了。

int maxLessThanFirst( int[] arr ) {
   int max = Integ3er.MIN_VALUE;
   for ( int i=1; i < arr.length; i++ ) {
      if ( arr[i] < arr[0] ) {
         <Do normal max value check here>
      }
   }
   return max;
}

请注意,在循环之后,如果 max=MIN_VALUE 您需要检查是否至少有一个值 = arr[0],则需要抛出异常表明没有解决方案。

【讨论】:

    【解决方案2】:

    您需要两个变量,一个用于存储第一个索引,以便进行比较,另一个用于在循环遍历数组时存储小于第一个索引的任何值。并且您不断将第二个值替换为低于当前值的任何数字。

    【讨论】:

      【解决方案3】:

      改变条件:

      if (max < numbers[endIndex]) {
      

      收件人:

      if (max < numbers[endIndex] && numbers[endIndex] < firstNumber) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-25
        • 1970-01-01
        • 2017-05-10
        • 2013-04-24
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多