题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
代码:
1 class Solution { 2 public: 3 void push(int value) { 4 st.push(value); 5 if( smin.empty()) 6 smin.push(value); 7 else{ 8 if(value <= smin.top()) //若当前值小于等于当前 smin 中栈顶元素则压入栈 9 smin.push(value); 10 } 11 } 12 void pop() { 13 if( !st.empty() ){ 14 if(st.top() == smin.top()) //若出栈元素与 smin 栈顶元素相同,则将其一并出栈 15 smin.pop(); 16 st.pop(); 17 } 18 } 19 int top() { 20 if( !st.empty() ) 21 return st.top(); 22 } 23 int min() { 24 if( !st.empty() ) 25 return smin.top(); 26 } 27 private: 28 stack<int> st; 29 stack<int> smin; // 用其栈顶指针表示最小元素 30 };
我的笔记:根据栈的先进后出原则,可以将当前栈的最小元素直接在另一栈中表示,即同样有先后顺序。