定义一个队列并实现函数max得到队列最大值,要求函数max,push_back和pop_front的时间复杂度都是O(1)
template<typename T>class QueueWithMax
{
public:
QueueWithMax() :currentIndex(0) {}
void push_back(T number)
{
while (!maxnums.empty() && number >= maxnums.back().number)
maxnums.pop_back();
InternalData internaldata = { number,currentIndex };
maxnums.push_back(internaldata);
data.push_back(internaldata);
++currentIndex;
}
void pop_front()
{
if(maxnums.empty())
throw new exception("queue is empty");
if (maxnums.front().index == data.front().index)
maxnums.pop_front();
data.pop_front();
}
T max() const
{
if (maxnums.empty())
throw new exception("queue is empty");
return maxnums.front().number;
}
private:
struct InternalData
{
T number;
int index;
};
deque<InternalData> data;
deque<InternalData> maxnums;
int currentIndex;
};