c++ - 下一个更大的元素

标签 c++ arrays loops

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        int arr[n];
        for (int i = 0; i < n; i++)
        {
            cin >> arr[i];
        }
        stack<int>s;
        stack<int>q;
        for (int i = n - 1; i > 0; i--)
        {
            s.push(arr[i]);
        }
        while (!s.empty())
        {
            int a = s.top();
            s.pop();
            int flag = 0;
            while (!s.empty())
            {
                int p = s.top();
                if (a >= p)
                {
                    q.push(p);
                    s.pop();
                }
                else {
                    cout << p;
                    flag = 1;
                    break;
                }
                p = s.top();
            }
            if (flag == 0)
            {
                cout << -1;
            }
            while (!q.empty())
            {
                s.push(q.top());
                q.pop();
            }

        }
    }
    return 0;
}

给定一个数组,打印每个元素的下一个更大元素 (NGE)。元素 x 的下一个更大元素是数组中 x 右侧的第一个更大元素。对于不存在更大元素的元素,将下一个更大元素视为-1。 为什么这段代码会出现段错误?

最佳答案

更改此:

for (int i = n - 1; i > 0; i--)

对此:

for (int i = n - 1; i >= 0; i--)

因为您想将所有元素插入堆栈。

之后,对于此输入:

1
3
1
2
3

我得到了预期的输出:

23-1

注意:正如 @John 所说,p = s.top(); 不执行任何操作,因此可以安全地删除它(因为 p 将退出无论如何)。

关于c++ - 下一个更大的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57131815/

相关文章:

c++ - 通过引用返回 vector

c++ - 功能模板的特化,不改变其原型(prototype)

arrays - O(n) 最坏情况下的 2D 峰值查找算法?

javascript - 如何重复显示数组中的每个元素并在单击按钮时停止

c++ - 命名空间内类的循环依赖问题

c++ - 如何根据引用进行 regex_replace

arrays - 使用掩码数组创建 pandas DataFrame

c - 将数组传递给 C 中的函数来存储数据

iphone - Objective-C中的高效循环

python - 计算 flask 模板中的行数