题目
类型:单调双栈 二分
题意:找到大于当前数的最小值。
版本1
set有序二分查找
34ms
class NextElement {
public:
vector<int> findNext(vector<int> A, int n) {
vector<int> res(n, -1);
set<int> st;
for(int i = n-1; i >= 0; i--){
auto it = upper_bound(st.begin(), st.end(), A[i]);
if(it != st.end()) res[i] = *it;
st.insert(A[i]);
}
return res;
}
};
版本2
双栈
20ms
class NextElement {
public:
vector<int> findNext(vector<int> A, int n) {
vector<int> res(n, -1);
stack<int> stk1,stk2;
for(int i = n-1; i >= 0; i--){
while(stk1.size() && A[stk1.top()] <= A[i]){
stk2.push(stk1.top());
stk1.pop();
}
if(stk1.size()) res[i] = A[stk1.top()];
stk1.push(i);
while(stk2.size()) { //转移栈
stk1.push(stk2.top());
stk2.pop();
}
}
return res;
}
};