【问题标题】:Get count from array using recursion使用递归从数组中获取计数
【发布时间】:2016-03-29 13:59:45
【问题描述】:

我需要使用递归来获得小于数组中第一个整数的数字的计数。我得到一个函数定义为

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

我不应该使用循环或全局/静态变量。如何转换下面的实现以满足上述两个条件。我最近问过another 类似的问题,但这有点不同,因为需要跟踪计数变量。如果有人可以提供帮助,我将不胜感激。 下面是我的循环实现。

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    int greater_than_first = 0;
    for (int count = startIndex; count <= endIndex; count++) {
        if (numbers[count] > firstNumber) {
            greater_than_first++;
        }
    }
    return greater_than_first;
}

【问题讨论】:

  • 它有效,但这不是预期的实现。

标签: java arrays recursion


【解决方案1】:

可能你不需要那么多参数:

public static int countGreaterThanFirst(int[] numbers, int currentIndex) {
    if (currentIndex == numbers.length) return 0;
    else {
        if (numbers[currentIndex] > numbers[0]) {
            return 1 + countGreaterThanFirst(numbers, currentIndex + 1);
        } else {
            return countGreaterThanFirst(numbers, currentIndex + 1);
        }
    }
}

你应该调用它(例如):

 countGreaterThanFirst(someArray, 1);

如果您要查找“numbers[startIndex]numbers[endIndex] 之间大于firstNumber 的所有数字,那么实现应该与上面的非常相似:

public static int countGreaterThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex > endIndex) return 0;
    else {
        if (numbers[startIndex] > firstNumber) {
            return 1 + countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber);
        } else {
            return countGreaterThanFirst(numbers, startIndex + 1, endIndex, firstNumber);
        }
    }
}

【讨论】:

  • 参数是条件。
  • 是的,我必须按照给定的定义实现该功能
  • 很遗憾,计数始终为 0。
  • 如何调用它?你为什么不尝试至少调试它?它在我的环境中运行良好。
  • @康斯坦丁感谢您的帮助。这是工作。我错误地调用它。
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 2015-03-13
  • 2017-10-11
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多