leetcode--901. 股票价格跨度(单调栈)

记录
10:00 2024-3-6

https://leetcode.cn/problems/online-stock-span/

维护一个单调递减的栈s,并且也要一个记录个数的栈count
每次来一个数据,这个数据如果比s栈顶数据小,就直接放入s,并在count中记录下它的个数1
如果这个数据比s栈顶数据大,就需要弹出s和count的top,来保证s是递减的,结果就是存在了count栈中

写的有点乱了,其实就是保证s递减,同时知道s中每个数据的count数(count指小于该数据的连续数据个数),这样来了一个数据,就可以通过维护递减栈来维护count栈,从而得到结果

点击查看代码
class StockSpanner {
public:
    // 存数值
    stack<int> s;
    // 存个数
    stack<int> count;
    StockSpanner() {
    }
    
    int next(int price) {
        if(s.empty() || price < s.top()){
            s.push(price);
            count.push(1);
        } else {
            int cnt = 0;
            while(!s.empty() && price >= s.top()) {
                cnt += count.top(); count.pop();
                s.pop();
            }
            s.push(price);
            count.push(cnt + 1);
        }
        return count.top();
    }
};

posted @ 2024-03-06 10:06  57one  阅读(2)  评论(0编辑  收藏  举报