Design a stack that supports push, POPs, 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. Example:minstack minstack = new Minstack () Minstack.push ( -2); Minstack.push (0); Minstack.push ( -3); Minstack.getmin (); --Returns-3.minstack.pop (); Minstack.top (); --Returns 0.minstack.getmin (); --Returns-2.subscribe to see which companies asked this question.
Test instructions: Design a stack with the Min function.
Public class minstack { private stack<integer> stackdata ; private stack<integer> stackmin; /** Initialize your data structure here. */ public minstack () { stackData=new Stack<Integer> (); stackMin=new Stack<Integer> (); } public void push (int x) { if (Stackmin.isempty ()) { stackmin.push (x); }else if (x<= Stackmin.peek ()) { stackmin.push (x); } stackdata.push (x); } /////here seems a bit of a problem .... Packaging class comparison .... public void pop () { if ( Stackdata.peek (). Equals (Stackmin.peek ())) { stackmin.pop (); } stackdata.pop (); } public int top () { return stackdata.peek (); } public int getmin () { return stackmin.peek (); }}/** * your minstack object will be instantiated and caLled as such: * minstack obj = new minstack (); * obj.push (x) ; * obj.pop (); * int param_3 = obj.top (); * int param_4 = obj.getmin (); */
PS: Defines a secondary stack. The minimum value to hold for each step. See also left teacher's book P1.
Leetcode 155. Min Stack Java language