Released: 17:29:18, September 22, 2021
Problem description and examples
Design a stack that supports push, pop and top operations and can retrieve the smallest element in a constant time.
push(x) -- pushes element x onto the stack.
pop() -- delete the element at the top of the stack.
top() -- get the stack top element.
getMin() -- retrieves the smallest element in the stack.
MinStack minStack = new MinStack();
minStack.getMin(); --> Return - 3
minStack.top(); --> Return 0
minStack.getMin(); --> Return - 2
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.
pop, top, and getMin operations are always called on non empty stacks.
However, the key point of this problem is that if the minimum value in the stack is obtained in constant time, it means that the data in the stack cannot be sorted temporarily to obtain the minimum value when calling getMin() function. So I thought of using a special array to save the subscript of the "previous" minimum value in the current MinStack instance. The tail of this array stores the subscript of the minimum value of "current" in the current MinStack instance.
Please refer to the notes below for detailed explanation:
Because the problem requires to find the minimum value in the stack in constant time, an additional array is specially used to save the historical minimum value, which is a typical practice of exchanging time for space.
Update: July 29, 2021 18:43:21
Because I consider the ownership of copyright, I won't paste the specific code in the [official solution], which can be viewed in the link below.
Update: September 22, 2021 17:34:17
reference resources: Minimum stack - minimum stack - LeetCode
[end of update]
Update: September 22, 2021 17:36:06