I did not think too much at first, I think the existing data structure in the standard library to spell, completely, this is my code:
classMinstack {Private: Multiset<int>Sortedelems; List<int>Stack; Public: voidPushintx) {Sortedelems.insert (x); Stack.push_back (x); } voidpop () {if(Stack.empty ()) {return; } sortedelems.erase (Sortedelems.find (Stack.back ())); Stack.pop_back (); } intTop () {returnStack.back (); } intgetmin () {return*Sortedelems.cbegin (); }};
This idea is a little lazy, that is, since you need to return the minimum element time is fixed, then the original theory needs to be used to find the cost I moved to other places, yes, I put them on the pop () he push ().
But after all, my algorithm is stupid, so the time to return to the minimum is shorter, but the total time is very long, inefficient, a total of 54ms.
When my method is not the fastest one, I will look at the discussion of other friends in the area, the result is found a more efficient way, the original code is the Java version, I rewritten a copy of my C + + version:
classMinstack {Private: Long LongMin =0; Stack<Long Long>_stack; Public: voidPushintx) {Auto&& n = static_cast<Long Long>(x); if(_stack.empty ()) {_stack.push (0L); Min=N; return; } _stack.push (n-min); if(N <min) {min=N; } } voidpop () {if(_stack.empty ()) {return; } Auto Popednum=_stack.top (); if(Popednum <0L) {min-=Popednum; } _stack.pop (); } intTop () {Auto Topnum=_stack.top (); if(Topnum >0) { returnstatic_cast<int> (min +topnum); } returnstatic_cast<int>(min); } intgetmin () {returnstatic_cast<int>(min); }};
This algorithm is very interesting, is a space to change the time of the strategy, my previous idea, the minimum value and the value stored in the stack is fragmented, storage is stored, and then find the minimum value alone.
This method is different, it is the minimum value with each value in the push () through the operation to establish a link, and in the pop () by inverse to obtain the original value, so the time is only 28ms.
Constructs a stack that can return the minimum element value within a fixed time