满足条件的数(快手)

输入一个一位数组,找出这个数组中,所有满足以下条件的元素:
1. 这个数左边的所有元素都小于他;
2. 这个数右边的数都大于他。
样例:
输入:			        输出:
[9, 15, 10, 11, 20, 39]  [9, 20, 39]

采用单调栈,入栈的条件:

  1. 如果当前的栈顶元素, st.top()>a[i],那么当前栈顶元素肯定不满足,所以需要一直pop,直到st.pop()<a[i];同时由于at.top()>a[i],所以a[i]也是不满足条件的,所以a[i]也没有权利入栈。
  2. 如果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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值