LeetCode刷题day27——单调栈

单调栈这里练习5道题,接雨水这题挺有意思的,没接触过这种做法。

739. 每日温度

(https://leetcode.cn/problems/daily-temperatures/)

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

示例 1:

输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

分析:

暴力解法搞不定,最后一个样例时间超限。我观察了,发现这个测试数据是每一轮都跑到了最后,导致时间复杂度真正到了n^2。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> result(temperatures.size(), 0);
        for (int i = 0; i < temperatures.size(); i++) {
            int j = i + 1;
            while (j < temperatures.size() &&
                   temperatures[j] <= temperatures[i]) {
                j++;
            }
            if (j == temperatures.size())
                result[i] = 0;
            else
                result[i] = j - i;
        }
        return result;
    }
};

单调栈是:加入的元素是单调的,一旦遇到不是单调的那个元素,就开始处理,弹栈。单调栈可以用在一个数组,求某个元素右边第一个比他大/小的元素。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        //单调栈:每次加入元素下标。要求:求出右边第一个比自己大的元素?即将入栈元素与栈顶元素比较大小,如果即将入站元素比栈顶大,找到了!!!处理结果数组,然后弹出栈顶,继续比较。直到栈顶元素大于此元素,将此元素入栈。
        vector<int> result(temperatures.size(), 0);
        stack<int> s;
        s.push(0);
        for (int i = 1; i < temperatures.size(); i++) {
            while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
                result[s.top()] = i - s.top();
                s.pop();
            }
            s.push(i);
        }
        return result;
    }
};

496. 下一个更大元素 I

(https://leetcode.cn/problems/next-greater-element-i/)

nums1 中数字 x下一个更大元素 是指 xnums2 中对应位置 右侧第一个x 大的元素。

给你两个 没有重复元素 的数组 nums1nums2 ,下标从 0 开始计数,其中nums1nums2 的子集。

对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j]下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1

返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素

示例 1:

输入:nums1 = [4,1,2], nums2 = [1,3,4,2].
输出:[-1,3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
- 1 ,用加粗斜体标识,nums2 = [1,3,4,2]。下一个更大元素是 3 。
- 2 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。

示例 2:

输入:nums1 = [2,4], nums2 = [1,2,3,4].
输出:[3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 2 ,用加粗斜体标识,nums2 = [1,2,3,4]。下一个更大元素是 3 。
- 4 ,用加粗斜体标识,nums2 = [1,2,3,4]。不存在下一个更大元素,所以答案是 -1 。

提示:

  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 104
  • nums1nums2中所有整数 互不相同
  • nums1 中的所有整数同样出现在 nums2

**进阶:**你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?

分析:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        for (int i = 0; i < nums1.size(); i++) {
            int index=0;
            for(int j=0; j<nums2.size(); j++) {//找到nums1在Nums2中对应的下标
                if(nums2[j]==nums1[i]) {
                    index=j;
                    break;
                }
            }
            int j=index;//下标找到,开始处理:找下一个更大的元素
            for(; j<nums2.size(); j++) {
                if(nums2[j]>nums2[index]) {
                    res.push_back(nums2[j]);
                    break;
                }
            }
            if(j==nums2.size())
                res.push_back(-1);
        }
        return res;
    }
};

503. 下一个更大元素 II

(https://leetcode.cn/problems/next-greater-element-ii/)

给定一个循环数组 numsnums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素

数字 x下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1

示例 1:

输入: nums = [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数; 
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。

示例 2:

输入: nums = [1,2,3,4,3]
输出: [2,3,4,-1,4]

提示:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

分析:

这题和上题的变化是:循环。可以找一圈,简单的想法是把数组复制一份拼在一起,遍历两倍数组的长度即可。注意观察代码,就是经典单调栈的写法,只是在循环条件上做了取模操作。

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        stack<int> s;
        vector<int> res(nums.size(), -1);
        s.push(0);
        for (int i = 1; i < nums.size()*2; i++) {//长度取两倍
            while(!s.empty()&&nums[i%nums.size()]>nums[s.top()]) {//下标还在范围内跑动
                res[s.top()] = nums[i%nums.size()];
                s.pop();
            }
            s.push(i%nums.size());
        }
        return res;
        
    }
};

42. 接雨水

(https://leetcode.cn/problems/trapping-rain-water/)

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例 1:

img

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

分析:

先来暴力解法:按列算,暴力解法无法通过。321 / 324 个通过的测试用例。

  • 思路一:暴力法。竖向每一个位置都查看,此位置能装多少雨水。以自己为底mid,向左找到最大的高度lheight,向右找到最大的高度rheight,此位置i能装的水为: h = min(lheight,rheight)-height[i];第一个和最后一个不能装雨水,跳过。
class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        for(int i=0;i<height.size();i++) {
            if(i==0||i==height.size()-1) continue;
            int lheight = 0;
            int rheight = 0;
            for(int j=0;j<i;j++)
                lheight = max(lheight,height[j]);
            for(int j=i+1;j<height.size();j++)
                rheight = max(rheight,height[j]);
            int h = min(lheight,rheight)-height[i];
            if(h>0)
            res+=h;
        }
        return res;
    }
};
  • 思路二:双指针法。按列算,先各自算出左右两边的最大高度。
class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        vector<int> right(height.size(),0);
        vector<int> left(height.size(),0);
        left[0] = height[0];
        //各自先计算
        for (int i = 1; i < height.size(); i++) {
            left[i] = max(height[i],left[i-1]);
        }
        right[height.size()-1] = height[height.size()-1];
        for(int i=height.size()-2;i>=0;i--) {
            right[i] = max(height[i],right[i+1]);
        }
        for(int i=0;i<height.size();i++) {
            int h = min(left[i],right[i])-height[i];
            if(h>0) {
                res+=h;
            }
        }
        return res;
    }
};
  • 思路三:单调栈法,用栈里的两个元素,作为左,底,待入栈元素作为右。按行算。图为代码随想录复制,如水印所示。

42.接雨水2

class Solution {
public:
    int trap(vector<int>& height) {
       int res=0;
        stack<int> s;
        s.push(0);
        for(int i=1;i<height.size();i++) {
            while(!s.empty()&&height[i]>height[s.top()]) {
                int mid = s.top();//底
                 s.pop();
                if(!s.empty()) {
                    int left = s.top();//左
                    int w = i-left-1;//右-左-1  得到宽度
                    int h=min(height[i],height[left])-height[mid];
                    res+=h*w;  
                }
            }
            s.push(i);
        }
        return res;
    }
};

84. 柱状图中最大的矩形

(https://leetcode.cn/problems/largest-rectangle-in-histogram/)

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

示例 1:

img

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10

示例 2:

img

输入: heights = [2,4]
输出: 4

提示:

  • 1 <= heights.length <=105
  • 0 <= heights[i] <= 104

分析:

暴力法,时间超限, 89 / 99 个通过的测试用例。

  • 为此,我们需要:

    左边看一下,看最多能向左延伸多长,找到大于等于当前柱形高度的最左边元素的下标;
    右边看一下,看最多能向右延伸多长;找到大于等于当前柱形高度的最右边元素的下标。

https://leetcode.cn/problems/largest-rectangle-in-histogram/solutions/142012/bao-li-jie-fa-zhan-by-liweiwei1419/g
图片是LeetCode里的,作者是liweiwei1419。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int res=0;
        for(int i=0;i<heights.size();i++){
            int left=i;
            int right=i;
            for(;left>=0;left--)
            if(heights[left]<heights[i])
            break;
            for(;right<heights.size();right++)
            if(heights[right]<heights[i])
            break;
            int w=right-left-1;
            int h=heights[i];
            res=max(res,h*w);
        }
        return res;
    }
};
  • 单调栈法:不管哪个方法,我们都是要找到位置mid为基准,左边第一个比它小,右边第一个比它小的位置。宽度就是: w = right - left - 1; S = w * heights[mid]。这个单调栈是栈头到栈底是递减的。
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int res = 0;
        stack<int> st;
        heights.push_back(0);
        heights.insert(heights.begin(), 0);
        for (int i = 0; i < heights.size(); i++) {
            while (!st.empty() &&heights[st.top()] > heights[i]) {
                int mid = st.top();
                st.pop();
                if (!st.empty()) {
                    int left = st.top();
                    int w = i - left - 1;
                    int h = heights[mid];
                    res = max(res, w * h);
                }
            }
            st.push(i);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值