zoukankan      html  css  js  c++  java
  • 牛客算法周周练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;
    }
    
  • 相关阅读:
    3.30一周拾遗
    3.25周 一周拾遗
    自动加载以及Composer的实现
    MySQL 事务处理
    PHP代码实现3 [函数角度]
    PHP代码实现2 [从变量和数据的角度] 1
    PHP代码实现2 [从变量和数据的角度] 2
    vue 报错: [Vue warn]: Error in nextTick: "RangeError: Maximum call stack size exceeded" 很可能是你的name错了
    vue电商开发记录1—实现电商图片放大镜,移入放大效果
    vue图片点击放大预览v-viewer
  • 原文地址:https://www.cnblogs.com/Hayasaka/p/14294213.html
Copyright © 2011-2022 走看看