牛客算法周周练15A - 数列下标(单调栈)

在这里插入图片描述

题目大意:

给出 n 个数,下标从 1 开始,依次输出 ai 右边第一个比 ai 大的数的下标,如果没有找到则输出 0 。

解题思路:

思路一:枚举
枚举从 i 到 n 所有的数,找到则输出第一个,没找到则输出 0 ,复杂度是平方阶的,范围1e4 复杂度大概1e8,很容易被卡。AC代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 1e4+50;
int a[N];
int main()
{
    memset(a, 0, sizeof a);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i ++)
        cin >> a[i];
    for (int i = 1; i <= n; i ++)
    {
        bool flag = true;
        for (int j = i+1; j <= n; j ++)
            if(a[j] > a[i])
            {
                cout << j << " ";
                flag = false;
                break;
            }
        if(flag)
          cout << 0 << " ";
    }
    cout << endl;
    //system("pause");
    return 0;
}

思路二:单调栈模拟
前面的方法复杂度过大,数据范围再大一点就不行了,这种方法用单调栈模拟,用栈维护一个不上升的序列,只要 a[i] < 栈顶则把 i 进栈,如果遇到比栈顶大的数,则说明这个数是栈里面的数要找的位置,栈内的数全部赋值 i ,然后 i 进栈,重新开始维护序列,让栈里面始终存不上升的序列。AC代码:

#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
const int N = 1e4+50;
int a[N], ans[N];
stack<int > st;
int main()
{
    memset(ans, 0, sizeof ans);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i ++)
        cin >> a[i];
    for (int i = 1; i <= n; i ++)
    {
        while (!st.empty() && a[i] > a[st.top()])//只要比栈顶大则把栈内元素要找的位置就是 i 
        {
            ans[st.top()] = i;
            st.pop();
        }
        st.push(i);
    }
    for (int i = 1; i <= n; i ++)
      cout << ans[i] << " ";
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值