- 现在我们有一个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){
stack<int> s;
s.push(-1);
int sz = A.size();
vector<int> res(sz);
int top;
for(int i = sz - 1; i >= 0; --i){
top = s.top();
while(top != -1 && A[i] >= top){
s.pop();
top = s.top();
}
s.push(A[i]);
res[i] = top;
}
return res;
}
};
- 这题还有一个变种是这样的:
- 现在有一个数组,请找出数组中每个元素的后面比它大的最小的元素,若不存在则为-1。
- 也就是记录的时候丢弃的数组要将其重新push到栈中来,若只是重复上题的做法的话可能会导致找出的数不是最小的。