716. Max Stack

Design a max stack that supports push, pop, top, peekMax and popMax.

push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5

Approach #2: Double Linked List + TreeMap [Accepted]

Intuition

Using structures like Array or Stack will never let us popMax quickly. We turn our attention to tree and linked-list structures that have a lower time complexity for removal, with the aim of making popMax faster than O(N)O(N) time complexity.

Say we have a double linked list as our "stack". This reduces the problem to finding which node to remove, since we can remove nodes in O(1)O(1) time.

We can use a TreeMap mapping values to a list of nodes to answer this question. TreeMap can find the largest value, insert values, and delete values, all in O(\log N)O(logN) time.

Algorithm

Let‘s store the stack as a double linked list dll, and store a map from value to a List of Node.

  • When we MaxStack.push(x), we add a node to our dll, and add or update our entry map.get(x).add(node).
  • When we MaxStack.pop(), we find the value val = dll.pop(), and remove the node from our map, deleting the entry if it was the last one.
  • When we MaxStack.popMax(), we use the map to find the relevant node to unlink, and return it‘s value.

The above operations are more clear given that we have a working DoubleLinkedList class. The implementation provided uses head and tail sentinels to simplify the relevant DoubleLinkedListoperations.

class MaxStack {
    TreeMap<Integer, List<Node>> map;
    DoubleLinkedList dll;

    public MaxStack() {
        map = new TreeMap();
        dll = new DoubleLinkedList();
    }

    public void push(int x) {
        Node node = dll.add(x);
        if(!map.containsKey(x))
            map.put(x, new ArrayList<Node>());
        map.get(x).add(node);
    }

    public int pop() {
        int val = dll.pop();
        List<Node> L = map.get(val);
        L.remove(L.size() - 1);
        if (L.isEmpty()) map.remove(val);
        return val;
    }

    public int top() {
        return dll.peek();
    }

    public int peekMax() {
        return map.lastKey();
    }

    public int popMax() {
        int max = peekMax();
        List<Node> L = map.get(max);
        Node node = L.remove(L.size() - 1);
        dll.unlink(node);
        if (L.isEmpty()) map.remove(max);
        return max;
    }
}

class DoubleLinkedList {
    Node head, tail;

    public DoubleLinkedList() {
        head = new Node(0);
        tail = new Node(0);
        head.next = tail;
        tail.prev = head;
    }

    public Node add(int val) {
        Node x = new Node(val);
        x.next = tail;
        x.prev = tail.prev;
        tail.prev = tail.prev.next = x;
        return x;
    }

    public int pop() {
        return unlink(tail.prev).val;
    }

    public int peek() {
        return tail.prev.val;
    }

    public Node unlink(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
        return node;
    }
}

class Node {
    int val;
    Node prev, next;
    public Node(int v) {val = v;}
}

  

Complexity Analysis

  • Time Complexity: O(\log N)O(logN) for all operations except peek which is O(1)O(1), where NN is the number of operations performed. Most operations involving TreeMap are O(\log N)O(logN).
  • Space Complexity: O(N)O(N), the size of the data structures used.
时间: 2024-11-09 01:52:51

716. Max Stack的相关文章

716. Max Stack - Easy

Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element i

[Twitter] Max Stack

Question: Design a max stack using one stack. ? One stack? I think it is two stacks. class MaxMinStack<T> {   private Stack<T> data;   private Stack<T> max;   private Stack<T> min;   private Comparator<T> comparator;      pub

[LeetCode] Max Stack 最大栈

Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element i

LeetCode Problems List 题目汇总

No. Title Level Rate 1 Two Sum Medium 17.70% 2 Add Two Numbers Medium 21.10% 3 Longest Substring Without Repeating Characters Medium 20.60% 4 Median of Two Sorted Arrays Hard 17.40% 5 Longest Palindromic Substring Medium 20.70% 6 ZigZag Conversion Ea

ELK stack 学习记录

ELK日志分析平台学习记录 首先ELK主要指elasticsearch .logstash 和kibana,三个开源软件组合而成的一套日志平台解决方案.可以将平时收集到的日志,通过前台展示出来,并且可以加以分析,理论上可以解放劳动力(再也不用干上生产取日志这种活了--很搓). 最近在研究ELKstack日志分析平台,网上相关的中文资料不多.所以呢也就写了这篇文章将自己的一些学习认识总结记录下来,基本偏实战,概念理论较少,概念这块,我想以后可以再开一篇文章来做一个阐述总结. 这篇文章中会先讲一下搭

Google interview question: count bounded slices(min/max queue)

Question: A Slice of an array said to be a Bounded slice if Max(SliceArray)-Min(SliceArray)<=K. If Array [3,5,6,7,3] and K=2 provided .. the number of bounded slice is 9, first slice (0,0) in the array Min(0,0)=3 Max(0,0)=3 Max-Min<=K result 0<=2

stack(顺序、链式及应用)

(java版) 1. 顺序栈的实现 顺序栈实现1 [java] package lang; import java.io.Serializable; import java.util.Arrays; /** * @ClassName: ArrayStack * @Description: 顺序栈 * @date 2014年1月20日 上午8:47:19 * @param <T> */ public class ArrayStack<T> implements Serializabl

【LeetCode】设计题 design(共38题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [146]LRU Cache [155]Min Stack [170]Two Sum III - Data structure design [173]Binary Search Tree Iterator [208]Implement Trie (Prefix Tree) [211]Add and Search Word - Data structure desig

BZOJ 1185 HNOI 2007 最小矩形覆盖 旋转卡壳

题目大意:给出平面上的一些点,问面积最小的矩形满足覆盖所有的点. 思路:覆盖问题和不是凸包上的点没关系,先做凸包.根据贪心的思想,这个覆盖了所有点的矩形肯定至少有一条边与凸包上的边重合,那么我们枚举凸包上的每一条边,对于这个已经确定了一条边的矩形,不难确定其他三个边.注意到已知当前直线的向量,就可以求出两侧和对面的向量,而这三个向量随着枚举的边的移动是单调的,所以就可以用旋转卡壳来卡住剩下的三条边. 但是旋转卡壳时的初值会出问题,如果按照逆时针的顺序求出剩下的三条边的时候,要想通过向量直接卡第三