算法D59 | 单调栈2 | 503.下一个更大元素II 42. 接雨水

文章讲述了两个常见的编程面试题,分别是使用单调栈解决的“接雨水”问题和“下一个更大元素”的变体。通过Python和C++代码展示了如何运用双指针和单调栈技术来求解这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

503.下一个更大元素II 

这道题和 739. 每日温度 几乎如出一辙,可以自己尝试做一做

代码随想录

Python:

739的nums扩展两倍即可。

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [-1]*n
        stk = [0]
        for i in range(1, 2*n):
            if nums[i%n] <= nums[stk[-1]]: 
                stk.append(i%n)
            else:
                while len(stk)>0 and nums[i%n]>nums[stk[-1]]:
                    result[stk[-1]] = nums[i%n]
                    stk.pop()
                stk.append(i%n)
        return result

C++:

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        int n = nums.size();
        vector<int> result(n, -1);
        stack<int> stk;
        stk.push(0);
        for (int i=1; i<2*n; i++) {
            if (nums[i%n]<=nums[stk.top()]) {
                stk.push(i%n);
            } else {
                while (!stk.empty() && nums[i%n]>nums[stk.top()]) {
                    result[stk.top()] = nums[i%n];
                    stk.pop();
                }
                stk.push(i%n);
            }
        }
        return result;
    }
};

42. 接雨水  

接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。

建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。

在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。 

代码随想录

Python:

class Solution:
    def trap(self, height: List[int]) -> int:
        result = 0
        stk = [0]
        for i in range(1, len(height)):
            while stk and height[i]>height[stk[-1]]:
                mid_h = stk.pop()
                if stk:
                    h = min(height[stk[-1]], height[i]) - height[mid_h]
                    w = i - stk[-1] - 1
                    result += h*w
            stk.append(i)
        return result

C++:

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> stk;
        stk.push(0);
        int result = 0;
        for (int i=1; i<height.size(); i++) {
            while (!stk.empty() && height[i]>height[stk.top()]) {
                int mid = stk.top();
                stk.pop();
                if (!stk.empty()) {
                    int h = min(height[stk.top()], height[i]) - height[mid];
                    int w = i - stk.top() - 1;
                    result += h*w;
                }
            }
            stk.push(i);
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值