如何解决我需要找到与slowChop具有类似功能的快速切割
我已经实现了 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 举报,一经查实,本站将立刻删除。