Https://mp.weixin.qq.com/s/q5wtEXg_tC-wlyK1uMlJJA Minimum Stack
Implement a minimal stack, step by step optimization, Space O (N) time O (1).
import Java.util.arraylist;import java.util.List;/** * @author Xiaoshi on 2018/9/1.*/ Public classMinstack {Privatelist<integer> data =NewArraylist<integer>(); Privatelist<integer> mins =NewArraylist<integer>(); Public voidPushintnum) {data.add (num); if(mins.size () = =0) { //Initialize minsmins.add (num); } Else { //secondary stack mins The minimum value per push intMin =getmin (); if(Num >=min) {mins.add (min); } Else{mins.add (num); } } } Public intpop () {//stack null, exception, return-1 if(data.size () = =0) { return-1; } //pop when two stacks sync popsMins.remove (Mins.size ()-1); returnData.remove (Data.size ()-1); } Public intgetmin () {//stack null, exception, return-1 if(mins.size () = =0) { return-1; } //returns the top element of the mins stack returnmins.Get(Mins.size ()-1); }}
[Algorithm optimization]
Time complexity O (1) space complexity is less than the preceding section of code. ,,, push
pop
top
getMin
are all O (1) time.
import Java.util.arraylist;import java.util.List;/** * @author Xiaoshi on 2018/9/1.*/ Public classMinstack {Privatelist<integer> data =NewArraylist<integer>(); Privatelist<integer> mins =NewArraylist<integer>(); Public voidPushintnum) throws Exception {data.add (num); if(mins.size () = =0) { //Initialize minsMins.add (0); } Else { //index of the secondary stack mins push minimum value intMin =getmin (); if(Num <min) {Mins.add (data.size ()-1); } } } Public intpop () throws Exception {//stack empty, throw exception if(data.size () = =0) { Throw NewException ("stack is empty"); } //Get index first when pop intPopindex = Data.size ()-1; //gets the top element of the mins stack, which is the minimum value index intMinindex = mins.Get(Mins.size ()-1); //if the index of the pop goes out is the minimum index, mins only out of the stack if(Popindex = =Minindex) {Mins.remove (mins.size ()-1); } returnData.remove (Data.size ()-1); } Public intGetmin () throws Exception {//stack empty, throw exception if(data.size () = =0) { Throw NewException ("stack is empty"); } //gets the top element of the mins stack, which is the minimum value index intMinindex = mins.Get(Mins.size ()-1); returnData.Get(Minindex); }}
Implementation and optimization of the minimum stack