因此,我正在尝试实现一种数据结构来处理动态顺序统计。数据结构具有以下操作:
- add(x):插入一个值为x的新元素
- get(k):返回第k小的元素:其中k = ceiling(n/a),其中n = 数据结构中的元素数量,a = 常量因子。
- reset:重置整个数据结构,即数据结构“为空”
我使用平衡的AVL树实现了我的数据结构。使用这个数据结构,操作的时间复杂度如下:
- add(x):O(log(n))
- get(k):O(log(n))
这是我用O(log(n))时间复杂度实现get(k)的代码:
public static int get(Node current, int k) {
int l = tree.sizeLeft(current) + 1;
if(k == l) {
return current.value;
} else if(k < l) {
if(current.left == null) {
return current.value;
}
return get(current.left, k);
} else {
if(current.right == null) {
return current.value;
}
return get(current.right, k);
}
}
这里是我为节点类编写的实现代码:
class Node {
int height, value, bal, size; // bal = balanceFactor, size = amount of nodes in tree
rooted at current node
Node leftChild = null;
Node rightChild = null;
public Node(int val) {
value = val;
height = 1;
size = 1;
}
然而,我的任务是实现一个数据结构,可以处理上述操作,并且 仅在获取(k)操作时花费O(1)(常数)时间。(添加(x)仍需花费O(log(n))时间)。同时,我不允许使用哈希表。
有没有可能修改我的实现以获得恒定时间? 或者,有哪种数据结构可以在恒定时间内处理获取(k)操作?
get
的时间复杂度为O(1)。除非add
的时间复杂度为O(n),否则我从未听说过动态顺序统计算法可以实现这一点。我的一个提醒是,除非编译器删除尾递归,否则你的get
确实使用O(log n)空间。你可以使用循环重新实现它。然后它将在O(1) _空间_上运行。 - GeneO(log a) = O(1)
的获取吗? - גלעד ברקןa
是一个常数,我们总是在寻找k = ceiling(n / a)
。你的例子似乎是无效的。根据问题,k
始终是ceiling(n / a)
。 - גלעד ברקן