美文网首页
算法-Stack堆栈题型

算法-Stack堆栈题型

作者: 码农朱同学 | 来源:发表于2022-08-08 17:05 被阅读0次

Stack栈

  • 特性:LIFO后进先出
  • 适用于需要记录之前的状态,必要的时候可以回到之前的状态,或者利用之前的值。
  • 不像array,不能用index访问,只能每次拿栈顶元素。

题外话:动态规划 Dynamic Programming

  • DP:记录之前所以状态,随时可能访问任何一个子问题,所以通常用Array或者HashTable,而且不会回到之前的状态,只会利用之前的值
  • Stack:每次只需要栈顶元素,并且每个状态只会被用O(1)次

Stack 原则

定义好Stack的含义

  • 在arr[i]左侧所以比arr[i]大的数
  • 递归之前的函数状态(Call Stack)

实例

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

push(x) —— 将元素 x 推入栈中。
pop()—— 删除栈顶的元素。
top()—— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

提示:

pop、top 和 getMin 操作总是在 非空栈 上调用。

public class LeetCode155 {

    public class MinStack {

        // 数据栈
        private Stack<Integer> data;
        // 辅助栈
        private Stack<Integer> helper;

        /**
         * initialize your data structure here.
         */
        public MinStack() {
            data = new Stack<>();
            helper = new Stack<>();
        }

        // 思路 1:数据栈和辅助栈在任何时候都同步

        public void push(int x) {
            // 数据栈和辅助栈一定会增加元素
            data.add(x);
            if (helper.isEmpty() || helper.peek() >= x) {
                helper.add(x);
            } else {
                helper.add(helper.peek());
            }
        }

        public void pop() {
            // 两个栈都得 pop
            if (!data.isEmpty()) {
                helper.pop();
                data.pop();
            }
        }

        public int top() {
            if (!data.isEmpty()) {
                return data.peek();
            }
            throw new RuntimeException("栈中元素为空,此操作非法");
        }

        public int getMin() {
            if (!helper.isEmpty()) {
                return helper.peek();
            }
            throw new RuntimeException("栈中元素为空,此操作非法");
        }
    }
}

相关文章

网友评论

      本文标题:算法-Stack堆栈题型

      本文链接:https://www.haomeiwen.com/subject/ujgwwrtx.html