输入一个一位数组,找出这个数组中,所有满足以下条件的元素:
1. 这个数左边的所有元素都小于他;
2. 这个数右边的数都大于他。
样例:
输入: 输出:
[9, 15, 10, 11, 20, 39] [9, 20, 39]
采用单调栈,入栈的条件:
- 如果当前的栈顶元素, st.top()>a[i],那么当前栈顶元素肯定不满足,所以需要一直pop,直到st.pop()<a[i];同时由于at.top()>a[i],所以a[i]也是不满足条件的,所以a[i]也没有权利入栈。
- 如果a[i]想要入栈,那么他要满足st.top()<a[i],并且还要满足a[i]之前的最大元素时要小于a[i]的,所以要维护一个最大值的变量。
#include <iostream>
#include <vector>
#include <stack>
#include <limits.h>
#include <algorithm>
using namespace std;
void solution(vector<int>& a)
{
stack<int> st;
int n = a.size();
int max_val = INT_MIN;
for(int i=0; i<n; ++i)
{
// max_val = max(max_val, a[i]);
if(st.empty()&&a[i]>max_val)
{
st.push(a[i]);
}else{
if(a[i]>st.top()&&a[i]>max_val)
st.push(a[i]);
else{
while(!st.empty() && a[i]<st.top())
{
st.pop();
}
}
}
max_val = max(max_val, a[i]);
}
while(!st.empty())
{
cout<<st.top()<<' ';
st.pop();
}
cout<<endl;
}
int main()
{
vector<int> test = {9, 15, 10, 11, 20, 39};
solution(test);
system("pause");
}