【问题标题】:Stack Implementation with getMiddle and getAt functions使用 getMiddle 和 getAt 函数实现堆栈
【发布时间】: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


【解决方案1】:
  • 首先是维护一个索引变量,比如index0
  • 当您执行push() 时,您会将元素添加到地图中,例如:
   void push(int value){
      // your code
      map.put(index++,your_node);
   }
  • 在你的pop(),你会这样做
int pop(){
   // your code
   your_node.prev.next = null;
   map.remove(index--);
}
  • 因此,获取中间元素只是在地图中查找
int middle(){
   // your code
   return map.get(index / 2).value;
}
  • k 处获取值将与上述类似:
int getKthElement(int K){
   // your code
   return map.get(K-1).value; // If K is above index, you can throw an exception
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多