Problem: Expand the stack, complete normal push and pop operations, and add the min (max) interface for accessing the smallest (large) elements, so that push, pop, the time complexity of Min is O (1 ).
The difficulty lies in how to maintain the minimum (large) value of the stack. It is impossible for all sorting and searching to achieve the minimum time complexity of O (1.
Idea: Exchange Space for time, as shown in. Add a minimum value stack to store the previous minimum value to maintain the current minimum value.
1. The elements in the stack are smaller than the current min. For example, if Min is 3, element 2 is in the stack, and the current minimum value is 3 pushed to the minimum value stack, and Min is 2.
2. The output stack element is the current min. For example, when Min is set to 1, element 1 is output from the stack, and element 2 of the minimum stack is output from the stack, min = 2. That is, it returns to the previous status.
The above is the minimum value obtained under the time O (1). The maximum value is the same as this, which can be achieved using an additional stack.
Code implementation:
#include<vector>#include<iostream>#include<assert.h>usingnamespace std; template<typenameT>classCStack{public: CStack():min_elem(0){} ~CStack(){} T&pop(); void push(const T& value); Tget_min() const;private: vector<T> _data; vector<size_t> _minstore; T min_elem;}; template<typenameT>T&CStack<T>::pop(){ assert( !_data.empty() ); T value; value = _data.back(); _data.pop_back(); if(value== min_elem){ min_elem =_minstore.back(); _minstore.pop_back(); } return value;} template<typenameT>voidCStack<T>::push(const T& value){ if(_data.empty()){ min_elem = value; } else if(value <= min_elem){ _minstore.push_back(min_elem); min_elem = value; } _data.push_back(value);}template<typenameT>TCStack<T>::get_min() const{ assert( !_data.empty() ); return min_elem;}intmain(){ CStack<int> s; s.push(3); int min = s.get_min(); cout<<"current min_elem:"<<min<<endl; s.push(4); s.push(5); min = s.get_min(); cout<<"current min_elem:"<<min<<endl; s.push(2); min = s.get_min(); cout<<"current min_elem:"<<s.get_min()<<endl; s.push(2); min = s.get_min(); cout<<"current min_elem:"<<min<<endl; s.pop(); cout<<"current min_elem:"<<s.get_min()<<endl; s.push(1); cout<<"current min_elem:"<<s.get_min()<<endl; return 0;}
O (1) time is used to calculate the minimum (large) element in the stack.