"155-min stack (minimum stack)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Design a stack, support push,pop,top, and find the smallest element operation (constant time)
Thinking of solving problems
Use a secondary stack to hold the smallest element in the stack.
Code Implementation
Algorithm implementation class
Public classMinstack {PrivateFinalStatic intDefault_size = +;Private int[] Stack;Private int[] minindex;Subscript for the smallest element in the stack that holds the first n data Private intmin = Integer.max_value;//To record the minimum data during the insertion process Private intindex =-1;//Record the position of the smallest element in the stack Private intCurrent =-1; Public Minstack() {stack =New int[Default_size]; Minindex =New int[Default_size]; } Public Minstack(intSize) {stack =New int[Size]; Minindex =New int[Size]; } Public void Push(intx) {current++;//move to the location you want to insert if(Current >= Stack.length) {//Capacity expansion int[] tmp =New int[Current *2]; System.arraycopy (Stack,0Tmp0, stack.length); stack = tmp; TMP =New int[Current *2]; System.arraycopy (Minindex,0Tmp0, minindex.length); Minindex = tmp; } Stack[current] = x;//Insert Data if(x < min) {//Save the minimum value insertedmin = x; index = current;//Record [0, current] The smallest element subscript is index} minindex[current] = index; } Public void Pop() {current--;if(Current >=0) {min = stack[minindex[current]];//Reset the minimum value in the stackindex = minindex[current];//Reset the index of the minimum value} } Public int Top() {if(Current <0) {Throw NewRuntimeException ("No more Data"); }returnStack[current]; } Public int Getmin() {if(Current <0) {Throw NewRuntimeException ("No more Data"); }returnStack[minindex[current]]; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47828195"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "155-min stack (minimum stack)"