c++ - Next Greater Element segfault 无法弄清楚
问题描述
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find the next greater element for each element of the array.
vector<long long> nextLargerElement(vector<long long> arr, int n){
// Your code here
vector<long long> res;
stack<long long> stk, resStack;
for(int i=n-1; i>=0; i--){
if(stk.empty()){
resStack.push(-1);
stk.push(arr[i]);
}
else{
while(!stk.empty() && stk.top() <= arr[i]) stk.pop();
resStack.push(stk.top());
stk.push(arr[i]);
}
}
while(!resStack.empty()){
res.push_back(resStack.top()), resStack.pop();
}
return res;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<long long> arr(n);
for(int i=0;i<n;i++)
cin>>arr[i];
Solution obj;
vector <long long> res = obj.nextLargerElement(arr, n);
for (long long i : res) cout << i << " ";
cout<<endl;
}
return 0;
} // } Driver Code Ends
给定一个大小为 N 的数组 arr[ ] 具有不同的元素,任务是按照它们在数组中出现的顺序为数组的每个元素找到下一个更大的元素。数组中元素的下一个更大的元素是右边最近的元素,它大于当前元素。如果当前元素不存在下一个更大的元素,则当前元素的下一个更大元素为-1。例如,最后一个元素的下一个较大的总是-1。
解决方案
推荐阅读
- scala - 如何从 Spark Executor 获取或创建 Hadoop 客户端
- binary - 执行位移操作(asr、lsl、lsr)
- python - 如何使用 Pynsist 在 python 中安装 numpy
- ios - UNNotification 中的“UN”代表什么?
- c - 函数自动返回指针,无需返回语句
- java - Native Script App build:gradle build 时面临的问题
- php - 如何在数据库中注册会话中保存的数据?
- java - 如何以编程方式加载 JDK 模块?
- python - 将美元转换为日元的 Python 编码失败
- android - 有没有办法在不停止播放的情况下以编程方式执行 YouTube 全屏操作?