Original title URL: https://www.lintcode.com/zh-cn/problem/min-stack/#
Implement a stack with a min method that takes the minimum value. The min method will return the minimum value in the current stack.
The stack you implement will support push , pop and min operations, all of which require O(1) time.
Precautions
The call to the min method cannot be made if there are no numbers on the stack
Sample
Do as follows: push(1), pop(), push(2), push(3), min(), push(1), min() returns 1, 2, 1
Label
Idea: You can create two arrays, one to hold the stack data, and the other to hold the minimum value of the current stack. Needless to say, the stack data array can be directly manipulated into and out of the stack.
Minimum value array, when a new element is pushed into the stack, it is determined which is the smaller of the current minimum value (the top of the stack) and the new element, and the smaller one is pushed into the minimum value array. When popping elements from the stack, just delete the last element of the minimum value array, and the two arrays are always the same length.
The min function can directly return the last element of the minimum value array, which is the current minimum value of the stack.
AC code:
class MinStack {
public:
MinStack () {
// do intialization if necessary
}
/*
* @param number: An integer
* @return: nothing
*/
void push(int number) {
// write your code here
m_iAarray.push_back(number);
if (minVal.empty()||number<minVal.back())
{
minVal.push_back(number);
}
else
{
minVal.push_back (minVal.back ());
}
}
/*
* @return: An integer
*/
int pop() {
// write your code here
int temp;
if (!m_iAarray.empty())
{
temp=m_iAarray.back();
m_iAarray.pop_back();
}
if (!minVal.empty())
{
minVal.pop_back();
}
return temp;
}
/*
* @return: An integer
*/
int min() {
// write your code here
return minVal.back();
}
vector<int> m_iAarray;
vector<int> minVal;
};
Reference: https://www.cnblogs.com/theskulls/p/5098271.html
Another idea is to use two stacks, one to save the data and one to save the current minimum value, which is more efficient. Reference: https://blog.csdn.net/ljlstart/article/details/48517703
When this method is pushed into the stack, it is judged whether the new element is less than or equal to the current minimum value (the top of the minimum value stack), and if it is less than the new value is pushed to update the minimum value stack, otherwise it remains the same.
When deleting an element, it is judged whether the value to be deleted is the current minimum value. If so, the minimum value stack deletes the current top of the stack and updates the minimum value.