zoukankan      html  css  js  c++  java
  • 实现一个特殊的栈,要求push,poll , getMin方法时间复杂度都是O(N)

    借助两个栈来实现

    public class GetMinStack {
    
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
    
        public GetMinStack() {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }
    
        public void push(int obj) {
            if (stackMin.isEmpty()) {
                stackMin.push(obj);
            } else {
                stackMin.push(obj < getmin() ? obj : getmin());
            }
            stackData.push(obj);
        }
    
        public int getmin() {
            if (stackMin.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            return stackMin.peek();
        }
    
        public int pop() {
            if (this.stackData.isEmpty()) {
                throw new RuntimeException("Your stack is empty.");
            }
            this.stackMin.pop();
            return this.stackData.pop();
        }
    
    }
  • 相关阅读:
    Reverse Linked List
    Sqrt(x)
    Convert Sorted Array to Binary Search Tree
    Remove Linked List Elements
    Happy Number
    Length of Last Word
    Pow(x, n)
    Rotate Image
    Permutations
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/moris5013/p/11627223.html
Copyright © 2011-2022 走看看