File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -184,6 +184,66 @@ if (l_max < r_max) {
184184![ labuladong] ( ../pictures/labuladong.jpg )
185185
186186
187+ [ eric wang] ( https://www.github.com/eric496 ) 提供 Java 代码
188+
189+ ``` java
190+ public int trap(int [] height) {
191+ if (height. length == 0 ) {
192+ return 0 ;
193+ }
194+
195+ int n = height. length;
196+ int left = 0 , right = n - 1 ;
197+ int ans = 0 ;
198+
199+ int l_max = height[0 ];
200+ int r_max = height[n - 1 ];
201+
202+ while (left <= right) {
203+ l_max = Math . max(l_max, height[left]);
204+ r_max = Math . max(r_max, height[right]);
205+
206+ if (l_max < r_max) {
207+ ans += l_max - height[left];
208+ left++ ;
209+ } else {
210+ ans += r_max - height[right];
211+ right-- ;
212+ }
213+ }
214+
215+ return ans;
216+ }
217+ ```
218+
219+ [ eric wang] ( https://www.github.com/eric496 ) 提供 Python3 代码
220+
221+ ``` python
222+ def trap (self , height : List[int ]) -> int :
223+ if not height:
224+ return 0
225+
226+ n = len (height)
227+ left, right = 0 , n - 1
228+ ans = 0
229+
230+ l_max = height[0 ]
231+ r_max = height[n - 1 ]
232+
233+ while left <= right:
234+ l_max = max (l_max, height[left])
235+ r_max = max (r_max, height[right])
236+
237+ if l_max < r_max:
238+ ans += l_max - height[left]
239+ left += 1
240+ else :
241+ ans += r_max - height[right]
242+ right -= 1
243+
244+ return ans
245+ ```
246+
187247[ 上一篇:如何运用二分查找算法] ( ../高频面试系列/koko偷香蕉.md )
188248
189249[ 下一篇:如何去除有序数组的重复元素] ( ../高频面试系列/如何去除有序数组的重复元素.md )
You can’t perform that action at this time.
0 commit comments