我有一组需要解决的递归问题。我已经完成了给我们的 4 个任务中的 3 个,但我很难理解最后一个任务。 我不一定想要实际的答案,但也许只是为我指明正确的方向,因为我什至不知道我的停止条件应该是什么。请注意,它必须是递归的,没有循环等。
预先感谢您提供的任何帮助!
Write recursive method arrayRange that returns the maximum integer minus the minimum integer in the filled array of ints. Use recursion; do not use a loop. The following assertions must pass (note the shortcut way to pass a reference to a new array--it saves your writing a bit of code (this passes an array built as a parameter):
assertEquals(2, rf.arrayRange(new int[] { 1, 2, 3 } ));
assertEquals(2, rf.arrayRange(new int[] { 3, 2, 1 } ));
assertEquals(0, rf.arrayRange(new int[] { 3 } ));
assertEquals(3, rf.arrayRange(new int[] { -3, -2, -5, -4 } ));
// Precondition: a.length > 0 public int arrayRange(int[] a)
最佳答案
停止条件是只剩下两项:最大值和最小值。然后只需返回差额即可。 (还要处理 1 或 0 项的情况,考虑测试用例中的输入。)
现在..如何减少每次传递的列表? :) 我会考虑一次检查前三个值(在这三个值中,只有两个应该保留在递归步骤中)。
快乐的家庭作业。
关于Java 作业帮助 - 数组递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440767/