java - 这种递归有什么意义?
问题描述
import java.util.*;
public class ArrayList5 {
static int max(ArrayList list) { // to be completed
if (list.size() == 0) {
return 0;
}
else
{
int first = (Integer) list.get(0);
list.remove(0);
if (first > max(new ArrayList(list)))
{
return first;
}
else
{
return max(list);
}
}
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 4, 5, 3, 2, 3, 1, 3);
// int t=Console.readInt("Enter Target:");
int res1 = max(new ArrayList(list));
System.out.println("max=" + res1);
}
}
我不明白为什么max(new ArrayList(list)))
需要该部分。为什么它必须创建一个新列表,为什么它不能继续使用一个列表?
另外为什么它不陷入循环(它是递归,所以它会不断发送一个新列表,所以我不明白为什么'first'不会每次都是4)?
解决方案
实际上,有很多多余的代码不是必需的,并且使代码变得繁琐/更难以阅读/理解。
您可以大大简化代码并摆脱对 ArrayList 的任何引用,这些引用并不是真正必要的,并通过在正确的位置使用适当的泛型,使代码真正可读。
您不需要在整个地方投射或创建列表。
public class ArrayList5 {
static int max(final List<Integer> list) {
if(list.isEmpty()) return 0;
final int head = list.get(0);
final List<Integer> tail = list.subList(1, list.size());
return (head > max(tail)? head:max(tail));
}
public static void main(final String... args) {
final int res1 = max(Arrays.asList(4, 5, 3, 2, 3, 1, 3));
System.out.printf("max=%d", res1);
}
}
推荐阅读
- java - 显示标题和图像但不显示内容的通知构建
- excel - 在按键上结束所有宏
- r - 选择用于绘图的纬度和经度范围
- python-3.x - 如何使用 p=set() 创建空集
- node.js - 如果标头中不存在 JWT 令牌,如何执行一些逻辑?
- linux - inotifywait 未在 bash 脚本中执行 while 循环
- aws-lambda - 来自 AWS Lambda 的 RDS 中的 SQL 死锁
- javascript - 为什么 fetch 在我的移动浏览器上不起作用?
- android - 有没有办法在应用程序被杀死时接收数据通知?
- python-2.7 - 循环遍历 OrderedDict 对象错误