zoukankan      html  css  js  c++  java
  • LeetCode -- Min Stack

    Question:

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.

    Analysis:

    设计一个栈,它能够支持push, pop, top操作,并且能够在常数时间内检索到最小的元素。

    solution1: 利用Java内置的Stack类,并且设置一个格外的栈,当每次有元素进栈时都判断是否是额外栈的最小元素。这样当求最小元素时直接peek额外栈的栈顶元素即可。

    solution2: 不适用Java内置的Stack类,每个栈节点维护一个最小值(是当前节点至栈底的最小值),其余操作与上面相同,只不过push,pop等基本操作要自己简单的实现一下。

    Answer:

    Solution1:

    class MinStack {
        private Stack<Integer> stack = new Stack<Integer>();
        private Stack<Integer> minStack = new Stack<Integer>();
        public void push(int x) {
            if(minStack.isEmpty() || x <= minStack.peek()) //if x is the minimum value
                minStack.push(x);
            stack.push(x);
        }
    
        public void pop() {
            if(stack.peek().equals(minStack.peek())) //if the pop value is the minimum
                minStack.pop();
            stack.pop();    
        }
    
        public int top() {
            return stack.peek();    
        }
    
         public int getMin() {
             return minStack.peek();
         }
    }

    Solution2:

    class MinStack {
       StackNode top = null;
        public void push(int x) {
            if(top == null) {
                    top = new StackNode(x);
                    top.min = x;
                    top.next = null;
            }
            else {
                    StackNode node = new StackNode(x);
                    if(x < top.min)
                        node.min = x;
                    else node.min = top.min;
                    node.next = top;
                    top = node;
            }
        }
    
        public void pop() {
            if(top != null)
                    top = top.next;
        }
    
        public int top() {
            if(top != null)
                    return top.val;
            else return 0;
        }
    
        public int getMin() {
            if(top != null)
                    return top.min;
            else return 0;
        } 
    }
    class StackNode {
        int val;
        int min; //store the min utile this node 
        StackNode next;
        public StackNode(int x) {
            val = x;
        }
    }
  • 相关阅读:
    HTTP Server
    分享:uSTL 2.0 发布,STL 标准模板库
    Boost.Asio和ACE之间关于Socket编程的比较
    使用BOOST实现简单的HTTP网页下载
    HTTP Client
    轩辕高端IT培训中心系昆山轩辕软件技术有限公司旗下的IT培训部门
    分享:链表实现的队列
    镕、喆、冇用五笔为何打不出来,在此向各位好友请教! 已回答 搜搜问问
    第一讲 Linux 编程入门与基本编程工具的使用
    C++03:使用Boost-用Asio实现简易Echo Server
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5190044.html
Copyright © 2011-2022 走看看