问题描述
我已经实现了 BinarySearchTree.slowChop,但需要实现更快的算法。
定义:
public BinarySearchTree<Node,T> chop(T x)
在元素 x 处将我们的有序集合分成两部分。包含元素 = x 的 SSet。这应该适用于所有元素,无论它们是否在此。
例如,假设 s={2,4,6,8}。然后 s.chop(3) 返回 {4,8} 并且 s 变为 {2}。对于 s.chop(4),我们会得到相同的结果。
slowChop
方法已实现,但需要 O(n) 时间,如果树是平衡的,则需要将其减少到至少 O(h)。
public BinarySearchTree<Node,T> slowChop(T x) {
Node sample = super.newNode();
BinarySearchTree<Node,T> other = new
BinarySearchTree<Node,T>(sample);
// Iterate through the n nodes in-order.
// When see value >=x,add to new BST in O(height) time,and
// remove it from this BST (on next iteration) in O(height) time.
Iterator<T> it = iterator();
T prev = null;
while( it.hasNext() ) {
T curr = (T)(it.next());
if( c.compare(curr,x) >= 0 ) { // we have our first >= x
other.add(curr);
if( prev != null ) {
this.remove(prev); // safe to remove Now
}
prev = curr;
}
}
if( prev != null ) {
this.remove(prev); // edge case,get that last one!
}
return other;
}
以下驱动器链接包含帮助器类:BinarySearchTree BinaryTree DefaultComparator SSet
https://drive.google.com/drive/folders/1Uc6pNFg8e3WyeiinVFk6yA4W0LdB6UGx?usp=sharing
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)