首页 > 代码库 > LeetCode Min Stack
LeetCode Min Stack
#include <iostream>#include <cstdlib>#include <vector>using namespace std;class MinStack2 {private: vector<pair<int, int> > mins; vector<int> stack;public: void push(int x) { stack.push_back(x); if (mins.size() == 0) { mins.push_back(make_pair(x, 1)); } else { int curr_min = mins.back().first; if (curr_min > x) { mins.push_back(make_pair(x, 1)); } else if (curr_min == x) { mins.back().second++; } else { // do nothing } } } void pop() { if (!stack.size()) { return; } int x = stack.back(); stack.pop_back(); if (x == mins.back().first) { if (--mins.back().second < 1) { mins.pop_back(); } } } int top() { if (!stack.size()) { return 0; } return stack.back(); } int getMin() { if (!stack.size()) { return 0; } return mins.back().first; }};class MinStack {private: vector<int> mins; vector<int> stack;public: void push(int x) { stack.push_back(x); if (mins.size() == 0) { mins.push_back(x); } else { if (mins.back() >= x) { mins.push_back(x); } } } void pop() { if (!stack.size()) { return; } if (stack.back() == mins.back()) { mins.pop_back(); } stack.pop_back(); } int top() { if (!stack.size()) { return 0; } return stack.back(); } int getMin() { if (!stack.size()) { return 0; } return mins.back(); }};int main() { MinStack stack; stack.push(3); stack.push(2); stack.push(3); cout<<stack.getMin()<<endl; stack.push(1); stack.push(1); cout<<stack.getMin()<<endl; stack.pop(); stack.pop(); cout<<stack.getMin()<<endl; return 0;}
同样的逻辑用java版本的就对,C++就内存超出,难道是vector默认翻倍涨的原因?
LeetCode Min Stack
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。