【发布时间】:2020-08-13 16:45:13
【问题描述】:
我需要使用以下函数创建类似于堆栈 (LIFO) 的数据结构:init()、push(Object)、pop()、getMiddle()、getAt(k)。 除了 getAt() 之外的所有函数的复杂度都应该是 O(1),而 getAt(k) 的时间复杂度应该是 O(log(k))。空间复杂度应该是 O(n)
问题在于 getAt(k) 函数,当 k 是堆栈中第 k 个插入(根据插入顺序)元素的索引时。 我决定使用 DoublyLinkedList,因为这样我就可以将指针移动到中间元素。我也分享一个代码。如果有人对我如何获得 O(k) 复杂度甚至解决方案有任何建议。
class Node {
Node prev;
Node next;
Object data;
int order; //index of inserted element
Node(Object data, int order) {
prev = null;
next = null;
this.data = data;
this.order = order;
}
}
public class LikeStack {
Node head;
Node mid;
int size;
//constructor
public LikeStack() {
this.size = 0;
this.head = null;
this.mid = null;
}
//push object to the stack and move the pointer to the middle of the stack if needed
public void push(Object o) {
size++;
Node toPush = new Node(o, size);
toPush.prev = null;
toPush.next = head;
if (size == 1) {
mid = toPush;
} else {
head.prev = toPush;
{
if (size % 2 == 1) {
mid = mid.prev;
}
}
}
head = toPush;
}
//pop object from the stack and move the pointer to the middle of the stack if needed
public Object pop() throws Exception {
if(size<=0)
{
throw new Exception("The stack is empty");
}
size--;
Object temp = head.data;
head=head.next;
if(head!=null)
{
head.prev=null;
}
if(size%2==1)
{
mid=mid.next;
}
return temp;
}
//just returning the middle element
public Object getMiddle(){
return mid.data;
}
【问题讨论】:
-
为什么你不能使用带有 DLL 的地图来使它 O(1) ?
-
getAt(k)可以在log(n)中完成而无需额外的数据结构,其中n是当前堆栈的大小。你确定log(k)是正确的要求吗? -
@SomeDude 是的,这是我作业中的问题,它是 log(k) 要求
-
@vivek_23 我想你能不能详细解释一下,因为我不知道如何用地图在恒定时间内做到这一点
-
@sirkol123 得到 O(1) 你只需构建一个插入索引的映射 -> 节点
标签: java algorithm data-structures stack time-complexity