zoukankan      html  css  js  c++  java
  • 【剑指offer】30.包含min函数的栈

    30.包含min函数的栈

    面试题30. 包含min函数的栈

    难度简单12

    定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是
    O(1)。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.min();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.min();   --> 返回 -2.
    

    思路:一个数据栈 一个最小值栈 在push的时候,将最小值存储到最小值栈中,pop的时候 直接pop出 当最小值栈中数据为空 将最大值添加进去。

    时间复杂度:o(1)

    空间复杂度:O(n)

    		Stack<Integer> dataStack;
            Stack<Integer> minStack;
            int minValue;
            /** initialize your data structure here. */
            public MinStack() {
                dataStack = new Stack();
                minStack = new Stack();
                minValue = Integer.MAX_VALUE;
            }   
            public void push(int x) {
                dataStack.push(x);
                minValue = Math.min(x,minValue);
                minStack.push(minValue);
            }
            public void pop() {
                dataStack.pop();
                minStack.pop();
                minValue = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
            }
            
            public int top() {
                return dataStack.peek();
            }
            
            public int min() {
                return minValue;
            }
    
  • 相关阅读:
    socket (一)
    yield生成器及字符串的格式化
    python模块(json和pickle模块)
    python标准模块(time、datetime及hashlib模块)
    python标准模块(os及sys模块)
    python模块简介
    python --> 正则表达式
    python --> 递归 以及装饰器
    python基础知识(四)
    python基础知识(三)
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860643.html
Copyright © 2011-2022 走看看