当前位置:网站首页>Design a stack with getmin function
Design a stack with getmin function
2022-06-28 13:49:00 【Hua Weiyun】
Design one with getMin Stack of functions
【 subject 】
Implement a special stack , On the basis of realizing the basic functions of stack , The operation of the smallest element in the return stack .
【 requirement 】
1.pop、push、getMin The time complexity of operation is O(1).
2. The designed stack type can use the existing stack structure .
【 Ideas 】
Use two stacks , A stack a Normal access , Another stack b Used to maintain the minimum value , Always keep b The top of the stack is the current a The minimum value in the stack .
Method 1 【 The depth of the two stacks is inconsistent 】: When entering the stack , Each entry a When the stack , If b The stack is empty. , Enter into a The stack enters at the same time b Stack , If you enter a Stack value ratio b The top of the stack is big , No entry , conversely , Get into b Stack , Update minimum ; Out of the stack , If the stack value is equal to b To the top of the stack , Just put b At the top of the stack , Update minimum , conversely ,b Stack does not update .
give an example : Press in in turn 3、4、5、1、2、1 In the process of ,stackData(a) and stackMin(b) The changes are shown in the figure below .
explain : The picture comes from Zuoshen's program code interview guide , For learning purposes only .

Method 2 【 The two stacks have the same depth 】: When entering the stack , Get into a Stack time , If b The stack is empty. , Get into b Stack , If b Stack is not empty and b Stack top less than a Stack new stack value , Then put the b The top of the stack is pushed again b Stack , The height is consistent ; Out of the stack , Both stacks pop up at the same time .
give an example : Press in in turn 3、4、5、1、2、1 In the process of ,stackData(a) and stackMin(b) The changes are shown in the figure below .

【 Code 】
【Java】
Method 1 :
package keafmd.accumulate.codeinterviewguide.stackwithgetmin;import java.util.Stack;/** * Keafmd * * @ClassName: getMinStack * @Description: Stack with minimum value * @author: Cowherd Conan * @date: 2022-06-20 14:29 */public class MyStack1 { private Stack<Integer> stacka; private Stack<Integer> stackb; public MyStack1(){ stacka = new Stack<>(); stackb = new Stack<>(); } // Push public void push(Integer val){ stacka.push(val); if(stackb.isEmpty()||val<=getMin()){ stackb.push(val); } } // Out of the stack public Integer pop(){ if(stacka.isEmpty()){ throw new RuntimeException("Stack is empty!"); } Integer val = stacka.pop(); if(val.equals(getMin())){ stackb.pop(); } return val; } // Get the minimum public Integer getMin(){ if(stackb.isEmpty()){ throw new RuntimeException("Stack is empty!"); } return stackb.peek(); }}Method 2 :
package keafmd.accumulate.codeinterviewguide.stackwithgetmin;import java.util.Stack;/** * Keafmd * * @ClassName: MyStack2 * @Description: Stack with minimum value * @author: Cowherd Conan * @date: 2022-06-20 15:07 */public class MyStack2 { private Stack<Integer> stacka; private Stack<Integer> stackb; public MyStack2(){ stacka = new Stack<>(); stackb = new Stack<>(); } // Push public void push(Integer val){ stacka.push(val); if(stacka.isEmpty()||val<getMin()){ stackb.push(val); }else{ stackb.push(getMin()); } } // Out of the stack public Integer pop(){ if(stacka.isEmpty()){ throw new RuntimeException("Stack is empty!"); } Integer val = stacka.pop(); stackb.pop(); return val; } // Get the minimum public Integer getMin(){ if(stackb.isEmpty()){ throw new RuntimeException("Stack is empty!"); } return stackb.peek(); }}【 summary 】
Method one and method two actually use stackb The stack holds stacka The minimum value of each step . The common point is that the time complexity of all operations is O(1)、 The complexity of space is O(n). The difference is that : In method one stackb Save space when pressing , But the pop-up operation takes a little time ; Method 2 stackb It takes a little space to press in , But the pop-up operation saves a little time .
边栏推荐
- 为什么新的5G标准将为技术栈带来更低的 TCO
- What is generics and how to use generics analysis
- 2022年中国运维安全产品市场规模及发展趋势预测分析
- 行动诠释价值,城联优品韩董事长出席广东英德抗洪捐赠公益活动会
- 欧拉恒等式:数学史上的真正完美公式!
- China Radio and television 5g package is coming, lower than the three major operators, but not as low as expected
- BERT为何无法彻底干掉BM25??
- 30 sets of JSP website source code collection "suggestions collection"
- Analysis and processing of GPS data format [easy to understand]
- 抢做意大利岛主?刘强东两月套现66亿 疑一次性5.6亿“紧急转账”急购欧洲海上皇宫
猜你喜欢

Why do more and more users give up swagger and choose apifox

If a programmer goes to prison, will he be assigned to write code?

Action interprets value. The chairman of chenglian Youpin Han attended the Guangdong Yingde flood fighting donation public welfare event

895. longest ascending subsequence

Other domestic mobile phones failed to fill the vacancy of Huawei, and apple has no rival in the high-end mobile phone market

Stackoverflow 2022 database annual survey

How to design data visualization platform

开源社邀您参加OpenInfra Days China 2022,议题征集进行中~

3. Overall UI architecture of the project
![(original) [Maui] realize](/img/76/d79b9cf4ed44870bb20a189315def9.jpg)
(original) [Maui] realize "floating action button" step by step
随机推荐
Connected to rainwater series problems
Prediction of red wine quality by decision tree
仅用递归函数和栈操作逆序一个栈
Summary of 2021 computer level III database
ThreadLocal的简单理解
Hubble database x a joint-stock commercial bank: upgrade the number management system of Guanzi, so that every RMB has an "ID card"
Special test for cold and hot start of app
Make an ink screen electronic clock, cool!
坐拥755万开发者的中国开源,进度几何?
几百行代码实现一个 JSON 解析器
Double buffer drawing
Unit test ci/cd
Idea global search shortcut settings
2021计算机三级数据库大题总结
Build a learning environment
【二叉树】从叶结点开始的最小字符串
En parlant d'exception - que se passe - t - il lorsque l'exception est lancée?
Operation and maintenance thinking | do you know the relationship between CMDB and monitoring?
GPS数据格式的分析与处理[通俗易懂]
【二叉树】在二叉树中分配硬币