下一个较大元素

来源:互联网 发布:经典网络推广文案 编辑:程序博客网 时间:2024/04/30 11:01

现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。
给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。
测试样例:

[11,13,10,5,12,21,3],7
返回:[13,21,12,12,21,-1,-1]

class NextElement {public:    vector<int> findNext(vector<int> A, int n) {        // write code here        vector<int> res(n);        stack<int> stc;        stc.push(-1);        for(int i = n - 1; i >= 0; --i){            while(stc.top() != -1 && A[i] > stc.top()){                stc.pop();            }            res[i] = stc.top();            stc.push(A[i]);        }        return res;    }};
0 0
原创粉丝点击