topic
Stack data structure definition, implement this type of stack can be a min function smallest element in the stack, call min, push and pop time complexity is O (1).
Example:
Mins Thanks mins thanks = new Mins Thanks ();
minStack.push (-2);
minStack.push (0);
minStack.push (-3);
minStack.min (); ->返回-3.
minStack.pop ();
minStack.top (); ->返回0.
minStack.min (); ->返回-2.
Note: The total number of calls each function does not exceed 20,000 times
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
Problem-solving ideas
Violence: min then traverse the call stack to find the smallest value of which, here, does not meet the subject requirements, not demonstration.
Stack
-
Features: last out
-
The title of the method needs to be implemented
- push (): at the end of the array to add one or more metal elements (pushed onto the stack)
- top (): Returns the last element (top element) array, but not in the stack
- pop (): delete the last element in the array (the top element from the stack)
Problem-solving
Stack contains min function, in fact, is more of a method than the min stack, call the minimum stack is returned.
It is only necessary to add an auxiliary storage stack to a smaller value, the call min () returns the auxiliary stack is the minimum stack top.
Code
- Execution Time: 24 ms - consumes memory: 8.5 MB
type MinStack struct {
nums []int //储存栈
min []int //辅助储存栈,存储最小值
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
make([]int,0,3),
make([]int,0,3),
}
}
func (this *MinStack) Push(x int) {
this.nums=append(this.nums,x)
if len(this.min)==0{
this.min=append(this.min,x)
}else if this.min[len(this.min)-1]<x{
this.min=append(this.min,this.min[len(this.min)-1])
}else{
this.min=append(this.min,x)
}
}
func (this *MinStack) Pop() {
this.nums=this.nums[:len(this.nums)-1]
this.min=this.min[:len(this.min)-1]
}
func (this *MinStack) Top() int {
return this.nums[len(this.nums)-1]
}
func (this *MinStack) Min() int {
return this.min[len(this.min)-1]
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Min();
*/
In LeetCode this question, I have to submit explanations, welcome to view. Nickname: Sakura.