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函数的栈
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 ****************************************************************/