加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

[LeetCode] Min Stack

发布时间:2020-12-13 20:06:59 所属栏目:PHP教程 来源:网络整理
导读: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() -- Retr

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.
解题思路:

主要是取得当前最小值的问题。我们可以用1个动态数组min存储当前最小值。若新压入的元素大于动态数组min最后1个元素,不做任何操作。否则(小于或等于)就压入min中。出栈的时候,若出栈元素等于min最后1个元素,则min数组出栈。这样便实现了常量时间找到栈中的最小值了。下面是代码:

class MinStack { public: MinStack(){ capcity=2; data = new int[capcity]; size=0; minCapcity=2; min = new int[minCapcity]; minSize = 0; } ~MinStack(){ delete[] data; delete[] min; } void push(int x) { if(size>=capcity){ int* p=data; capcity = 2*capcity; data=new int[capcity]; std::memcpy(data,p,sizeof(int)*size); delete[] p; } data[size++]=x; if(minSize==0){ min[minSize++]=x; }else if(min[minSize⑴]>=x){ if(minSize>=minCapcity){ int* p=min; minCapcity = 2*minCapcity; min = new int[minCapcity]; std::memcpy(min,sizeof(int)*minSize); delete[] p; } min[minSize++]=x; } } void pop() { if(size>0){ size--; if(data[size]==min[minSize⑴]){ minSize--; } }else{ throw exception(); } } int top() { if(size>0){ return data[size⑴]; }else{ throw exception(); } } int getMin() { return min[minSize⑴]; } private: int size; int capcity; int* min; int minSize; int minCapcity; int* data; };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读