这是在leetcode中solution给出的一种很新颖的解法,利用了栈的结构,通过维护一个非递增栈来得到答案。 本质思想还是利用了要存水必须是“两高夹一矮”这个特点,只不过这里是用非递增栈来实现。 下面定义一些符号以便理解: stack[-1] 栈顶元素 stack[-2] 栈顶的下面一个元素(即倒数第二个元素) solution4的整个算法是这么实现
首先用两个数组,max_left [ i ] 代表第 i 列左边最高的墙的高度,max_right [ i ] 代表第 i 列右边最高的墙的高度。(一定要注意下,第 i 列左(右)边最高的墙,是不包括自身的,和 leetcode 上边的讲的有些不同) 对于max_left 我们其实可以这样求。 max_left [ i ] = Max ( max_left [ i -...
LeetCode 42. Trapping Rain Water(Hard) image! Example: Solution 该题很有意思,可以当作是在砌墙:输入一个数组,数组元素可以当作当前位置墙的高度,问该种情况,能装多少水(可以这么理解,不过实际上是2维平面,只考虑面积...较少的那一个。 先分享一个错误的想法: 可以通过一次遍历找到所有可以“装水”的gap...
换而言之,这种遍历的方法是遍历求每个横坐标单位上所能trap住的water,即 在这个单位横坐标上所能trap的water减去这个单位上竖条所占的面积: 代码: classSolution {publicinttrap(int[] height) {intwater=0;for(inti=0;i<height.length;i++){intmax_left=0;intmax_right=0;for(intj=i;j>=0;j--){ m...
https://leetcode-cn.com/problems/trapping-rain-water/ 题目内容 给定n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 示例图 示例: 输入: [0,1,0,2,1,0,1,3,2,1,2,1] 输出: 6 思路 我们可以设置两个数组,「left_height_array」和「right_height_array...
LeetCode Trapping Rain Water LeetCode解题之Trapping Rain Water 原题 计算一个凹凸不平的模型中能够存放多少的雨水。 以下图为例,黑色的地方是砖块。蓝色的地方是积水。 注意点: 给的參数数组表示的是砖块的高度(它自身也要占面积),不仅仅是边 不会存在负数的情况...
https://oj.leetcode.com/problems/trapping-rain-water/ 这道题使用单调队列能够O(n)时间解决。维护一个降序排列的单调队列。如果Ai>A[que.front]就说明能够使用que.front作为顶部计算一次积水。 当从0-n时,须注意队列中还有元素。需要反向再执行一次单调队列。但是只需要到之前队列的front的位置即可。
可以参考官网的 solution,有配图: leetcode-solution code #include<iostream>#include<vector>#include<algorithm>#include<stack>usingnamespacestd;classSolution{public:inttrap(vector<int>& height){//return trap_brute_force(height);//return trap_dynamic_programming(height);//return trap_stack(height);ret...
Solution 解题描述 Trapping Rain Water 题解 题目来源:https://leetcode.com/problems/trapping-rain-water/description/ Description Givennnon-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. ...
LeetCode (42): Trapping Rain Water 【描述】 Givennnon-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given[0,1,0,2,1,0,1,3,2,1,2,1], return6....