con = left# 往右找h, con = l[0] l.sort(reverse=True, key=cmp_to_key(Solution.mcmp))foriinrange(1,len(l)): val, right = l[i]ifright > con:forjinrange(con+1, right): ans += val - height[j] con = rightreturnans C++解法
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 ## 接不住任何雨水 ## 初始化左右指针 ...
result +=max(0,min(h, maxh[i]) - height[i])returnresultif__name__ =="__main__":assertSolution().trap([0,1,0,2,1,0,1,3,2,1,2,1]) ==6 欢迎查看我的Github(https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。
AI代码解释 classSolution{publicinttrap(int[]height){int result=0;if(height.length==0)returnresult;int[]left_height_array=newint[height.length];int[]right_height_array=newint[height.length];int left_max=0;int right_max=0;left_height_array[0]=0;right_height_array[0]=0;for(int i=1;i...
class Solution: """ @param heights: a list of integers @return: a integer """ def trapRainWater(self, heights): if not heights: return 0 left_max = [] curt_max = -sys.maxsize for height in heights: curt_max = max(curt_max, height) left_max.append(curt_max) right_max = []...
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 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 ...
LeetCode 42. Trapping Rain Water(Hard) image! Example: Solution 该题很有意思,可以当作是在砌墙:输入一个数组,数组元素可以当作当前位置墙的高度,问该种情况,能装多少水(可以这么理解,不过实际上是2维平面,只考虑面积...较少的那一个。 先分享一个错误的想法: 可以通过一次遍历找到所有可以“装水”的gap...
leetCode(trapping-rain-water)-数组最多能装多少水 题目:给定一个数组,数组中的每一个元素代表一个高度,问由数组中的元素组成的桶总共能装多少水。 Given[0,1,0,2,1,0,1,3,2,1,2,1], return6. 思路:与前面数组容器最多能装多少水采用类似的方法,双指针一头一尾遍历一遍,每次移动短板,在移动短板...