• 牛客算法周周练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;
    }
    
  • 相关阅读:
    c# 遍历DataTable
    c# 判断网络状态
    c# 发送Http 请求
    c# 处理Json字符串
    环境搭建(Nginx + PHP7 + Mysql + 运行ThinkPHP5项目)
    c# 获取时间戳
    php 处理 byte
    微信小程序 滚动至元素底部
    mysql 删除 多个字段相同的 重复的 数据
    微信小程序 跑马灯效果
  • 原文地址:https://www.cnblogs.com/Hayasaka/p/14294213.html
Copyright © 2020-2023  润新知