首页 > 解决方案 > 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。

标签: c++

解决方案


推荐阅读