【发布时间】:2017-01-20 10:20:44
【问题描述】:
该方法返回二叉树中不包含的最小非负整数。
例子:
用 0 1 2 3 返回 4。
1 2 3 4 返回 0。
用 0 1 2 5 6 返回 3。
用 6 1 5 2 返回 3。
我的解决方案的复杂性是 O(n^2)。如何在不超过 O(n) 的时间内解决?
public static <E> int minIntNotContains(BinTree<Nodo<Integer>> node) {
List<Integer> a=new ArrayList<Integer>();
int min=minIntNotContainsRic(node,a);
return min;
}
public static <E> int minIntNotContainsRic(BinTree<Nodo<Integer>> node,List<Integer> a) {
int min= node.getValue().getValue();
a.add(node.getValue().getValue());
if(node.getLeftSubtree() != null) {
min = Math.min(min, minIntNotContainsRic(node.getLeftSubtree(),a));
}
if(node.getRightSubtree() != null) {
min = Math.min(min, minIntNotContainsRic(node.getRightSubtree(),a));
}
if (min>0) return 0;
else{
for (int i=0;i<a.size();i++){
if (!a.contains(i+1)){
return i+1;
}
}
return min;
}
}
【问题讨论】:
-
为什么
1 2 5 6不返回0? -
你怎么知道这是 O(n^2)?为什么需要在每个递归调用中循环遍历列表?
-
是不是特殊的二叉树,比如搜索树?或者只是任何二叉树?
-
0 是非负数。如果你的意思是积极的,为什么
1 2 3 4返回 0?如果 0 表示“不丢失整数”,为什么0 1 2 3返回 4? -
那么答案是 theta(N) 表示空间和时间复杂度,因为您总是需要遍历整棵树,因为对于较低级别(您对较低级别的值或树的任何部分一无所知)
标签: java algorithm time-complexity binary-tree