将每一个点的高度和索引存成一个元组 (val, idx) 找到最高的点(可能有多个,任取一个),记为 (now_val, now_idx)。 向左找第一个val不大于now_val的点(left_val, left_idx)。 以left_val作为水平面,用height[left_val+1, now_val-1]中每一个点更新ans。 now_val, now_idx = left_
Python 解法一:两指针的高效解法 ## LeetCode 42H - Trapping Rain Water,双指针法 from typing import List class Solution: ## height 表示列表中元素的取值,高度 def trap(self, height: List[int]) -> int: if not height: ## 如果没有任何高度 return 0 ## 接不住任何雨水 ## 初始化左右指针 ...
[LeetCode]题解(python):042-Trapping Rain Water 题目来源 https://leetcode.com/problems/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...
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...
water; } } 赞同 72 条评论 Tin 更新于 2/14/2021, 6:57:36 AM python3 如果目的是给出一个最优解,双指针是空间O(1)的最优解。 如果用这题练习单调栈的话,可以参考我的两个尝试。 Solution_value_stack 是把高度值放到一个递降单调栈里,这个单调栈不是严格的单调栈,只有当进栈值大于栈首时才开始...
42. Trapping Rain Water 难度:hard 总结一下:一类解法是像我刚开始想的那样,一个坑一个坑地考虑,另一种则是一个位置一个位置地考虑。 My solution O(n^2): 第一个遇到的bar作为一个容器的左面,那么此容器的右面有两种可能: 如果右边存在高于它的bar,那么它和第一个高于它的bar形成一个容器,中间的bar全...
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! class Solution(object): def trap(self, height): ...
42.Trapping rain water 看到这道题目,我的思路起始于从左到右遍历,但是没有left_max和right_max的概念,完全实施不了具体的算法。 而是转换思路,从下到上遍历,但是这种又需要每次从左到右遍历,而且在左右两端的判断我也不清楚如何进行。遂放弃。 成熟的两种思路第一种思路完全依赖于left_max和right_max的概念,...
42. Trapping Rain Water Given n non-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. avatar The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 ...
题目来源:https://leetcode-cn.com/problems/trapping-rain-water/ 今天在LeetCode上看到一道很有意思的题目:接雨水。题目给出了一些柱子的高度,然后要求出这些柱子可以装的水有多少。 我想到的方法是从左往右遍历数组,记录当前的最高的柱子高度,只要遇到比最高柱子低的柱子,就假设这个柱子可以装下(最高柱子高度-...