给定一个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) {
// write code here
vector<int> res(n,-1);
for(int i = 0; i < n; i++){
int mi = INT_MAX;
int flag = 0;
for(int j = i+1; j < n; j++){
if(A[j] > A[i]){
mi = A[j];
flag = 1;
break;
}
}
if(flag) res[i] = mi;
}
return res;
}
};
方法二
class NextElement {
public:
vector<int> findNext(vector<int> A, int n) {
// write code here
vector<int> res;
if(n <= 0) return res;
stack<int> tmp;
tmp.push(-1);
for(int i = n-1; i >= 0; --i){
while(tmp.top() != -1 && A[i] > tmp.top()) tmp.pop();
res.insert(res.begin(), tmp.top());
tmp.push(A[i]);
}
return res;
}
};
最后面的一定是-1,所以先把-1推入栈内,再从后往前逐个检索。