思想:
在利用push建栈的过程中,边 “建栈” 边 "利用数组保留当前压栈后的最大的那个元素,即只需要比较数组中的前一个元素即可,若比前一个元素大,则保留该元素到数组中,否则保留数组中的前一个元素相同的值。"
则当前栈中的最大的元素即使该数组中的最后一个元素。时间复杂度为O(1)
解决: g++ 编译环境
/*
* main.cpp
*
* Created on: 2009-6-18
* Author: NeeSky
*/
#define MAXSIZE 100
#include <iostream>
using namespace std;
/**
* The definition of Stack
*/
struct Stack
{
int size;
int data[MAXSIZE];
};
/**
* The Global Variables
*/
Stack stackProblem;
int arrayAssistant[MAXSIZE];
/**
* Push the element to stackProblem ,
* and record the element max to arrayAssistant
* */
inline void push(int element )
{
if (stackProblem.size >= MAXSIZE) /*Overflow Obeverse*/
{
cerr << "Push:The stackProblem is full ! " << endl;
return;
}
stackProblem.data[stackProblem.size] = element;
arrayAssistant[stackProblem.size++] = element
> arrayAssistant[stackProblem.size - 1] ? element
: arrayAssistant[stackProblem.size - 1];
return;
}
/**
* Pop the element from stackProblem return the element
* */
inline int pop()
{
if (stackProblem.size == 0)
{
cerr << "Pop: The stackProblem is empty ! " << endl;
return -1;
}
return stackProblem.data[--stackProblem.size];
}
/**
* Fill the array to stack
* */
void fill_Stack()
{
int A[10] = { 0 };
for (int i = 0; i < 10; ++i)
{
A[i] = rand() ;
cout<<A[i]<<" ";
}
cout<<endl;
for (int i = 0; i < 10; i++)
{
push(A[i]);
}
return;
}
/**
* O(1) Time Complex: get the max value from Stack
* */
int getMax_fromStack()
{
return arrayAssistant[stackProblem.size - 1];
}
int main(void )
{
fill_Stack();
cout << getMax_fromStack() << endl;
return 0;
}
输出:
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
29358