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、pop、top和在常量时间内检索最小元素的栈。 push(x) —— 推送元素X进栈 pop() —— 移除栈顶元素top() —— 得到栈顶元素getMin() —— 检索栈的最小元素利用两个vector来实现,一个实现正常的栈,一个在压栈的时候存储最小元素,在检索栈的最小元素的时候直接取最小栈的栈顶元素即可。代码如下:
1 class MinStack { 2 public: 3 /** initialize your data structure here. */ 4 vector<int> allstack; 5 vector<int> minstack; 6 MinStack() { 7 8 } 9 10 void push(int x) { 11 if(allstack.empty()) 12 { 13 allstack.push_back(x); 14 minstack.push_back(x); 15 } 16 else 17 { 18 allstack.push_back(x); 19 if(x <= minstack[minstack.size()-1]) 20 { 21 minstack.push_back(x); 22 } 23 } 24 } 25 26 void pop() { 27 if(allstack[allstack.size()-1] == minstack[minstack.size()-1]) 28 { 29 minstack.pop_back(); 30 } 31 allstack.pop_back(); 32 } 33 34 int top() { 35 return allstack[allstack.size()-1]; 36 } 37 38 int getMin() { 39 return minstack[minstack.size()-1]; 40 } 41 }; 42 43 /** 44 * Your MinStack object will be instantiated and called as such: 45 * MinStack obj = new MinStack(); 46 * obj.push(x); 47 * obj.pop(); 48 * int param_3 = obj.top(); 49 * int param_4 = obj.getMin(); 50 */
时间: 2024-12-16 12:54:56