题目描述
现在我们有一个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> result;
stack<int> stk;//用于保存比当前值都大的数
stk.push(-1);
for(int i=n-1;i>=0;i--){
int temp=stk.top();
while(temp!=-1&&temp<A[i]){
stk.pop();//弹出比当前元素小的数
temp=stk.top();
}
result.insert(result.begin(),temp);
stk.push(A[i]);
}
return result;
}
};