[LeetCode]Min Stack,解题报告

目录

  • 目录
  • 题目
  • 思路1
    • AC代码
    • 缺陷
  • 思路2
    • AC代码

题目

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.

思路1

这道题算是面试过程中比较简单的题目,在实现基础栈的基础上,增加了一个在O(1)时间复杂度下获取当前栈内最小值的需求。

很自然的可以想到,可以用ArrayList来构建stack,同时用一个int类型的变量minIndex作为当前最小值的下标。

  • 每次push(x)操作时,判断是否需要更新minIndex。
  • 每次pop操作时,判断当前移除的是否为minIndex,如果是,则需要O(n)时间复杂度更新minIndex。

思路有了,我们可以先写代码尝试一下,这种思路是否可以AC这道题目。

AC代码

import java.util.ArrayList;

public class MinStack {
    private ArrayList<Integer> stack = new ArrayList<Integer>();
    private int minIndex = 0;

    public void push(int x) {
        stack.add(x);
        if (x < stack.get(minIndex) || stack.size() == 1) {
            minIndex = stack.size() - 1;
        }
    }

    public void pop() {
        if (minIndex == stack.size() - 1) {
            minIndex = 0;
            for (int i = 1; i < stack.size() - 1; i ++) {
                if (stack.get(i) < stack.get(minIndex)) {
                    minIndex = i;
                }
            }
        }

        stack.remove(stack.size() - 1);
    }

    public int top() {
        return stack.get(stack.size() - 1);
    }

    public int getMin() {
        return stack.get(minIndex);
    }
}

缺陷

虽然上面的代码可以AC,而且getMin()方法的时间复杂度是O(1),但是我们在pop方法中,当需要更新minIndex时,花费的时间复杂度是O(n),严格的说,上面的代码是不符合面试要求的。

减少时间复杂度最便捷的方法就是增加空间复杂度,很自然的我们想到“双栈法”。再维护一个最小数的栈,这样更新minIndex的操作我们可以通过最小数出栈的方式来搞定了。


思路2

双栈法的思路是:增加一个最小栈。当最小栈为空或者当前push元素小于等于最小栈栈顶元素时,该push元素也要push到最小栈中。

AC代码

import java.util.Stack;

public class MinStack {
    private Stack<Integer> normalStack = new Stack<Integer>();
    private Stack<Integer> minStack = new Stack<Integer>();

    public void push(int x) {
        if (minStack.size() == 0 || x <= minStack.peek()) {
            minStack.push(x);
        }
        normalStack.push(x);
    }

    public void pop() {
        if (normalStack.peek().equals(minStack.peek())) {
            minStack.pop();
        }

        normalStack.pop();
    }

    public int top() {
        return normalStack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}
时间: 2024-07-30 21:24:17

[LeetCode]Min Stack,解题报告的相关文章

LeetCode: Min Stack 解题报告

Min Stack My Submissions Question Solution 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

【LeetCode】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 mini

LeetCode: Combination Sum 解题报告

Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The

[LeetCode]LRU Cache, 解题报告

题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

[LeetCode] Min Stack Min Stack

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

LeetCode ZigZag Conversion 解题报告

对输入字符串,做蛇形变化,然后按行输出. https://oj.leetcode.com/problems/zigzag-conversion/ 例如:The string "PAYPALISHIRING"  的蛇形变化如下: P        A           H        N A   P   L    S     I     I   G Y         I            R 最后要求输出的就是:"PAHNAPLSIIGYIR" Write

LeetCode——Min Stack

Description: 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

[leetcode] Min Stack @ Python

原题地址:https://oj.leetcode.com/problems/min-stack/ 解题思路:开辟两个栈,一个栈是普通的栈,一个栈用来维护最小值的队列. 代码: class MinStack: # @param x, an integer def __init__(self): self.stack1 = [] self.stack2 = [] # @return an integer def push(self, x): self.stack1.append(x) if len(