改良stack的push操作,使得从stack中获取最大元素的时间复杂度为O(1) [转]

思想:

       在利用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

转载于:https://my.oschina.net/yx00001/blog/35418

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值