C++实现LeetCode(155.最小栈)

[LeetCode] 155. Min Stack 最小栈

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

这道最小栈跟原来的栈相比就是多了一个功能,可以返回该栈的最小值。使用两个栈来实现,一个栈来按顺序存储 push 进来的数据,另一个用来存出现过的最小值。代码如下:

C++ 解法一: 

class MinStack {
public:
    MinStack() {}
    void push(int x) {
        s1.push(x);
        if (s2.empty() || x <= s2.top()) s2.push(x);
    }
    void pop() {
        if (s1.top() == s2.top()) s2.pop();
        s1.pop();
    }
    int top() {
        return s1.top();
    }
    int getMin() {
        return s2.top();
    }

private:
    stack<int> s1, s2;
};

Java 解法一:

public class MinStack {
    private Stack<Integer> s1 = new Stack<>();
    private Stack<Integer> s2 = new Stack<>();

    public MinStack() {}
    public void push(int x) {
        s1.push(x);
        if (s2.isEmpty() || s2.peek() >= x) s2.push(x);
    }
    public void pop() {
        int x = s1.pop();
        if (s2.peek() == x) s2.pop();
    }
    public int top() {
        return s1.peek();
    }
    public int getMin() {
        return s2.peek();
    }
}

需要注意的是上面的 Java 解法中的 pop() 中,为什么不能用注释掉那两行的写法,博主之前也不太明白为啥不能对两个 stack 同时调用 peek() 函数来比较,如果是这种写法,那么不管 s1 和 s2 对栈顶元素是否相等,永远返回 false。这是为什么呢,这就要看 Java 对于peek的定义了,对于 peek() 函数的返回值并不是 int 类型,而是一个 Object 类型,这是一个基本的对象类型,如果直接用双等号 == 来比较的话,肯定不会返回 true,因为是两个不同的对象,所以一定要先将一个转为 int 型,然后再和另一个进行比较,这样才能得到想要的答案,这也是 Java 和 C++ 的一个重要的不同点吧。

那么下面再来看另一种解法,这种解法只用到了一个栈,还需要一个整型变量 min_val 来记录当前最小值,初始化为整型最大值,然后如果需要进栈的数字小于等于当前最小值 min_val,则将 min_val 压入栈,并且将 min_val 更新为当前数字。在出栈操作时,先将栈顶元素移出栈,再判断该元素是否和 min_val 相等,相等的话将 min_val 更新为新栈顶元素,再将新栈顶元素移出栈即可,参见代码如下:

C++ 解法二: 

class MinStack {
public:
    MinStack() {
        min_val = INT_MAX;
    }
    void push(int x) {
        if (x <= min_val) {
            st.push(min_val);
            min_val = x;
        }
        st.push(x);
    }
    void pop() {
        int t = st.top(); st.pop();
        if (t == min_val) {
            min_val = st.top(); st.pop();
        }
    }
    int top() {
        return st.top();
    }
    int getMin() {
        return min_val;
    }
private:
    int min_val;
    stack<int> st;
};

Java 解法二:

public class MinStack {
    private int min_val = Integer.MAX_VALUE;
    private Stack<Integer> s = new Stack<>();

    public MinStack() {}
    public void push(int x) {
        if (x <= min_val) {
            s.push(min_val);
            min_val = x;
        }
        s.push(x);
    }
    public void pop() {
        if (s.pop() == min_val) min_val = s.pop();
    }
    public int top() {
        return s.peek();
    }
    public int getMin() {
        return min_val;
    }
}

Github 同步地址:

https://github.com/grandyang/leetcode/issues/155

类似题目:

Sliding Window Maximum

Max Stack

参考资料:

https://leetcode.com/problems/min-stack/

https://leetcode.com/problems/min-stack/discuss/49014/java-accepted-solution-using-one-stack

https://leetcode.com/problems/min-stack/discuss/49016/c-using-two-stacks-quite-short-and-easy-to-understand

到此这篇关于C++实现LeetCode(155.最小栈)的文章就介绍到这了,更多相关C++实现最小栈内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(153.寻找旋转有序数组的最小值)

    [LeetCode] 153. Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. You may

  • C++实现LeetCode(151.翻转字符串中的单词)

    [LeetCode] 151.Reverse Words in a String 翻转字符串中的单词 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-p

  • C++实现LeetCode(149.共线点个数)

    [LeetCode] 149. Max Points on a Line 共线点个数 Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example 1: Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | |        o |     o |  o   +------------->

  • C++实现LeetCode(147.链表插入排序)

    [LeetCode] 147. Insertion Sort List 链表插入排序 Sort a linked list using insertion sort. A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is

  • C++实现LeetCode(150.计算逆波兰表达式)

    [LeetCode] 150.Evaluate Reverse Polish Notation 计算逆波兰表达式 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integ

  • C++实现LeetCode(152.求最大子数组乘积)

    [LeetCode] 152. Maximum Product Subarray 求最大子数组乘积 Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has

  • C++实现LeetCode(148.链表排序)

    [LeetCode] 148. Sort List 链表排序 Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5 常见排序方法有

  • C++实现LeetCode(154.寻找旋转有序数组的最小值之二)

    [LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值之二 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. Th

  • C++实现LeetCode(155.最小栈)

    [LeetCode] 155. Min Stack 最小栈 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. getM

  • python实现时间o(1)的最小栈的实例代码

    这是毕业校招二面时遇到的手写编程题,当时刚刚开始学习python,整个栈写下来也是费了不少时间.毕竟语言只是工具,只要想清楚实现,使用任何语言都能快速的写出来. 何为最小栈?栈最基础的操作是压栈(push)和退栈(pop),现在需要增加一个返回栈内最小值的函数(get_min),要求get_min函数的时间复杂度为o(1).python的栈肯定是使用list实现,只要将list的append和pop封装到stack类中,即实现了压栈和退栈.如果不考虑时间复杂度,我们第一反应一定是min(),mi

  • C++实现LeetCode(64.最小路径和)

    [LeetCode] 64. Minimum Path Sum 最小路径和 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in t

  • C++实现LeetCode(76.最小窗口子串)

    [LeetCode] 76. Minimum Window Substring 最小窗口子串 Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BA

  • 手把手带你了解C++最小栈

    目录 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈. 示例: 输入: 输出: 解释: 思路 总结 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x 推入栈中. pop() -- 删除栈顶的元素. top() -- 获取栈顶元素. getMin() -- 检索栈中的最小元素. 示例: 输入: ["MinStack","push","push&quo

  • 用PHP解决的一个栈的面试题

    前言 遇到一道面试题,题目大概意思如下: 使用两个普通栈实现一个特殊栈,使得pop.push.min三个函数的都是复杂度为O(1)的操作,min函数是获得当前栈的最小值. 初步想法 1.要实现min函数为(1)操作,当时第一想法是事先需要算好当前最小值,于是会想到用一个值来保存当前栈中最小值元素,然后push和pop操作的时候维护这个值.这样min,push都是O(1)了,但pop可不是,如果当前弹出的是最小值,需要从新寻找当前元素的最小值,这个就不是o(1)了. 2.而且上面方法没有用到另外一

  • Java数据结构专题解析之栈和队列的实现

    目录 1. 栈 1.1 概念 1.2 助解图题 1.3 栈的数组实现 1.4 问题 1.5 栈的单链表实现 2. 队列 2.1 概念 2.2 问题 2.3 队列的单链表实现 2.4 数组实现队列 2.5 循环队列 2.6 双端队列 3. 栈和队列练习题 3.1 有效的括号 3.2 用队列实现栈 3.3 用栈实现队列 3.4 实现一个最小栈 3.5 设计循环队列 1. 栈 1.1 概念 栈:是一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作. 特点:栈中的数据元素遵循先进后出的原则,但

  • Java 栈与队列实战真题训练

    目录 1.实现循环队列 (1)数组下标实现循环 (2)区分队列的满与空 2.队列实现栈 3.栈实现队列 4.实现最小栈 1.实现循环队列 [OJ链接] 循环队列一般通过数组实现.我们需要解决几个问题. (1)数组下标实现循环 a.下标最后再往后(offset 小于 array.length): index = (index + offset) % array.length.通俗一点,就是如果我们的数组大小为8,下标走到了7,再往后如何回到0,我们可以(index+1)%8来实现. b.下标最前再

  • C++ 超详细讲解stack与queue的使用

    目录 stack 介绍和使用 模拟实现 stack的使用例题 最小栈 栈的弹出压入序列 逆波兰表达式求值 queue 模拟实现 容器适配器 deque简介 priority_queue优先级队列 priority_queue的使用 priority_queue的模拟实现 通过仿函数控制比较方式 stack 介绍和使用 stack文档介绍 stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行元素的插入与提取操作. stack是作为容器适配器被实现的,容器适

  • C++实现LeetCode(111.二叉树的最小深度)

    [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度 Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no child

随机推荐