给定一个int数组A及其大小n,返回一个int数组,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) { vector<int> result; if(n <= 0){ return result; }//if stack<int> stack; stack.push(-1); for(int i = n-1;i >= 0;--i){ int top = stack.top(); while(top != -1 && A[i] >= top){ stack.pop(); top = stack.top(); }//while result.insert(result.begin(),top); stack.push(A[i]); }//for return result; } };
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题