【LeetCode】Min Stack && 【九度】题目1522:包含min函数的栈

1、【LeetCode】Min Stack
Min Stack
Total Accepted: 15869 Total Submissions: 102810 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 element.
getMin() -- Retrieve the minimum element in the stack.
【解题思路】
1、采用辅助包含最小数的栈。
2、每次入栈时,判断栈顶元素和即将入栈数大小,如果入栈数较小,就存入最小栈。
3、每次出栈时,判断出栈元素和最小栈栈顶元素是否相等,如果相等,两个都出栈。
4、这样就保证最小栈的栈顶元素一定是当前最小元素。

Java AC 298ms

class MinStack {
    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    
    public void push(int x) {
        if(minStack.isEmpty() || x <= minStack.peek()){
            minStack.push(x);
        }
        stack.push(x);
    }

    public void pop() {
        int x = stack.pop();
        if(x == minStack.peek()){
            minStack.pop();
        }
    }

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

    public int getMin() {
        return minStack.peek();
    }
}

Python AC 232ms

class MinStack:
    stack = []
    minStack = []

    def __init__(self):
        self.stack = []
        self.minStack = []

    # @param x, an integer
    # @return an integer
    def push(self, x):
        if not self.minStack or x <= self.minStack[len(self.minStack) - 1]:
            self.minStack.append(x)
        self.stack.append(x)

    # @return nothing
    def pop(self):
        x = self.stack.pop()
        if x == self.minStack[len(self.minStack) - 1]:
            self.minStack.pop()

    # @return an integer
    def top(self):
        return self.stack[len(self.stack) - 1]

    # @return an integer
    def getMin(self):
        return self.minStack[len(self.minStack) - 1]

2、【九度】题目1522:包含min函数的栈
时间限制:1 秒内存限制:128 兆特殊判题:否提交:1539解决:493
题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(1<=n<=1000000), n代表将要输入的操作的步骤数。
接下来有n行,每行开始有一个字母Ci。
Ci=’s’时,接下有一个数字k,代表将k压入栈。
Ci=’o’时,弹出栈顶元素。
输出:
对应每个测试案例中的每个操作,
若栈不为空,输出相应的栈中最小元素。否则,输出NULL。
样例输入:
7
s 3
s 4
s 2
s 1
o
o
s 0
样例输出:
3
3
2
1
2
3
0
【阶梯思路】
和1一样。

Java AC

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Stack;
 
public class Main {
    /*
     * 1522
     */
    public static void main(String[] args) throws Exception {
        StreamTokenizer st = new StreamTokenizer(new BufferedReader(
                new InputStreamReader(System.in)));
        while (st.nextToken() != StreamTokenizer.TT_EOF) {
            int n = (int) st.nval;
            Stack<Integer> stack = new Stack<Integer>();
            Stack<Integer> minStack = new Stack<Integer>();
            for (int i = 0; i < n; i++) {
                st.nextToken();
                String s = st.sval;
                if (s.equals("s")) {
                    st.nextToken();
                    int num = (int) st.nval;
                    stack.push(num);
                    if (minStack.isEmpty() || num < minStack.peek()) {
                        minStack.push(num);
                    }
                } else if (s.equals("o")) {
                    int num = stack.pop();
                    if (num == minStack.peek()) {
                        minStack.pop();
                    }
                }
                if (minStack.isEmpty()) {
                    System.out.println("NULL");
                } else {
                    System.out.println(minStack.peek());
                }
            }
        }
    }
}
 
/**************************************************************
    Problem: 1522
    User: wzqwsrf
    Language: Java
    Result: Accepted
    Time:860 ms
    Memory:26968 kb
****************************************************************/
C++ AC

#include <stdio.h>
#include <stack>
using namespace std;
int n;
char s[1];
int num;
int main(){
    while(scanf("%d",&n) != EOF){
        stack<int> allStack;
        stack<int> minStack;
        for (int i = 0; i < n; i++) {
            scanf("%s",s);
            if (s[0] == 's') {
                scanf("%d", &num);
                if (minStack.empty() || num <= minStack.top()) {
                    minStack.push(num);
                }
                allStack.push(num);
            }else if(s[0] == 'o'){
                num = allStack.top();
                allStack.pop();
                if (num == minStack.top()) {
                    minStack.pop();
                }
            }
            if (minStack.empty()) {
                printf("NULL\n");
            }else{
                printf("%d\n", minStack.top());
            }
        }
    }
}
 
/**************************************************************
    Problem: 1522
    User: wzqwsrf
    Language: C++
    Result: Accepted
    Time:20 ms
    Memory:1052 kb
****************************************************************/



你可能感兴趣的:(【LeetCode】Min Stack && 【九度】题目1522:包含min函数的栈)