力扣题:单调栈-11.3

力扣题-11.3

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:901. 股票价格跨度

解题思想:通过栈记录(idx, price)的组合即可

在这里插入图片描述

class StockSpanner(object):

    def __init__(self):
        self.stack = [(-1, float('inf'))]
        self.idx = -1


    def next(self, price):
        """
        :type price: int
        :rtype: int
        """
        self.idx += 1
        while price >= self.stack[-1][1]:
            self.stack.pop()
        self.stack.append((self.idx, price))
        return self.idx - self.stack[-2][0]

class StockSpanner {
public:
    std::stack<std::pair<int, int>> stack;
    int idx = -1;
    
    StockSpanner() {
        stack.push({-1, INT_MAX});
    }
    
    int next(int price) {
        idx +=1;
        while(price>=stack.top().second){
            stack.pop();
        }
        stack.push({idx, price});
        pair<int, int> temp = stack.top();
        stack.pop();
        pair<int, int> temp2 = stack.top();
        stack.push(temp);
        return idx - temp2.first;
    }
};

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner* obj = new StockSpanner();
 * int param_1 = obj->next(price);
 */

力扣题2:42. 接雨水

解题思想:通过栈保存(i, height)的组合,保持栈是递减的

在这里插入图片描述

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """

        stack = []
        result= 0
        for i in range(len(height)):
            while stack and stack[-1][1] < height[i]:
                temp = stack.pop()
                if not stack:
                    break
                current = stack[-1]
                width = i - current[0]-1
                high = min(current[1], height[i]) - temp[1]
                result += width * high
            stack.append((i,height[i]))
        return result
class Solution {
public:
    int trap(vector<int>& height) {
        std::stack<std::pair<int, int>> stack;
        int result =0;
        for(int i=0;i<height.size();i++){
            while(!stack.empty() && stack.top().second<height[i]){
                pair<int, int> temp = stack.top();
                stack.pop();
                if(stack.empty()){
                    break;
                }
                pair<int, int>  current = stack.top();
                int width = i-current.first -1;
                int high =0;
                if(current.second<height[i]){
                    high = current.second - temp.second;
                }
                else{
                    high = height[i] - temp.second;
                }
                result+=width*high;
            }
            stack.push({i,height[i]});
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值