栈——下一个较大值

 

 我的题解:

#include<stack>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int a[100010];
int res[100010];
int main()
{
    int t;
    cin>>t;
    int n;

    while(t--)
    {
        stack <int> st;
        cin>>n;
        for(int i=0; i<n; i++)
            //scanf("%d",&a[i]);
            cin>>a[i];

        for(int i=n-1; i>=0; i--)
        {
            while(!st.empty())
            {
                if(st.top()>a[i])
                {
                    res[i]=st.top();
                    st.push(a[i]);
                    break;
                }
                else st.pop();
            }

            if(st.empty())
            {
                res[i]=-1;
            }
            st.push(a[i]);
        }
        for(int i=0; i<n; i++){
            //cout<<a[i]<<"-->"<<res[i]<<endl; 这里使用cout<<endl;超时了,因为输入少的时候cout<<endl 和其他差不多,但是输出多的时候差别很大
             printf("%d-->%d",a[i],res[i]);
             cout<<'\n';
    }}
    return 0;
}

 

posted @ 2023-04-01 16:34  小花护符  阅读(11)  评论(0编辑  收藏  举报