https://leetcode.com/problems/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.
思路:
关键在于找最小值要O(1)复杂度,所以空间换时间。一个额外的vector存储递减序入栈的数字。
AC代码:
1 class MinStack { 2 public: 3 MinStack(){ st_min.push_back(INT_MAX); }; 4 void push(int x) { 5 if (x <= st_min[st_min.size()-1]) 6 st_min.push_back(x); 7 st.push_back(x); 8 return; 9 } 10 11 void pop() { 12 if (st[st.size() - 1] == st_min[st_min.size() - 1]){ 13 st_min.pop_back(); 14 } 15 st.pop_back(); 16 return; 17 } 18 19 int top() { 20 return st[st.size() - 1]; 21 } 22 23 int getMin() { 24 return st_min[st_min.size() - 1]; 25 } 26 27 private: 28 vector<int> st; 29 vector<int> st_min; 30 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步