《Cracking the Coding Interview》——第3章:栈和队列——题目2
2014-03-18 05:16
579 查看
2014-03-18 05:08
题目:实现一个栈,除了能进行push和pop之外,还能在O(1)时间内返回栈中最小的元素。
解法:用另一个“最小栈”存放最小的元素,每当有不小于当前最小值的元素进栈时,就代表最小值更新了(就算与当前最小值相等,也代表个数变了)。这时,同时要将最小值进栈。这个最小栈的栈顶就是最小的元素。出栈时,遇到数据栈的栈顶元素与最小栈相等时,要同时将最小栈出栈;否则只弹出数据栈即可。
代码:
题目:实现一个栈,除了能进行push和pop之外,还能在O(1)时间内返回栈中最小的元素。
解法:用另一个“最小栈”存放最小的元素,每当有不小于当前最小值的元素进栈时,就代表最小值更新了(就算与当前最小值相等,也代表个数变了)。这时,同时要将最小值进栈。这个最小栈的栈顶就是最小的元素。出栈时,遇到数据栈的栈顶元素与最小栈相等时,要同时将最小栈出栈;否则只弹出数据栈即可。
代码:
// 3.2 Design a modified stack that in addition to Push and Pop can also provide minimum element present in the stack via Min function. #include <climits> #include <cstdio> #include <cstring> #include <stack> using namespace std; class MinStack { public: bool empty() { return st.empty(); } void push(int val) { st.push(val); if (min_st.empty() || val <= min_st.top()) { min_st.push(val); } } void pop() { if (st.empty()) { return; } if (st.top() == min_st.top()) { min_st.pop(); } st.pop(); } int top() { if (st.empty()) { return INT_MIN; } return st.top(); } int min() { if (st.empty()) { return INT_MIN; } return min_st.top(); } private: stack<int> st; stack<int> min_st; }; int main() { char s[100]; int op; MinStack st; while (scanf("%s", s) == 1 && strcmp(s, "END") != 0) { if (strcmp(s, "PUSH") == 0) { scanf("%d", &op); st.push(op); printf("push=%d\n", op); } else if (strcmp(s, "POP") == 0) { op = st.top(); st.pop(); printf("pop=%d\n", op); } else if (strcmp(s, "TOP") == 0) { printf("top=%d\n", st.top()); } else if (strcmp(s, "MIN") == 0) { printf("min=%d\n", st.min()); } } return 0; }
相关文章推荐
- coding--SSL理解总结
- 产品经理 深入浅出(3)
- 16.5.6: <fmt:parseDate>标签
- 16.5.5: <fmt:formatDate>标签
- 16.5.4: <fmt:parseNumber>标签
- 16.5.3: <fmt:formatNumber>标签
- 16.5.2: <fmt:timeZone>标签
- 《Cracking the Coding Interview》——第3章:栈和队列——题目1
- 内存数据库VoltDB, B轮融资8百万美元,总计近2千万美元
- Moravec角点检测算法原理
- java interface 用法
- coding---进程、线程的回收
- LeetCode 之排序 sorting
- 新人第一篇
- MVC二级联动使用$.getJSON方法
- Binary Tree Preorder Traversal -- LeetCode
- 完全依赖XP必将自食其果
- vijos 1243 单调队列优化dp
- 002_030 Python CRC 64位循环冗余码校验
- C# RichTextBox 获取当前光标的行号列号