File tree Expand file tree Collapse file tree 1 file changed +65
-1
lines changed
Expand file tree Collapse file tree 1 file changed +65
-1
lines changed Original file line number Diff line number Diff line change @@ -182,7 +182,7 @@ int trap(vector<int>& heights)
182182
183183### 代码
184184
185- 代码支持 Python3,C++:
185+ 代码支持 Python3,C++, Go :
186186
187187```python
188188class Solution:
@@ -232,6 +232,70 @@ public:
232232};
233233```
234234
235+ ```go
236+ func trap(height []int) int {
237+ if len(height) == 0 {
238+ return 0
239+ }
240+
241+ l, r := 0, len(height)-1
242+ lMax, rMax := height[l], height[r]
243+ ans := 0
244+ for l < r {
245+ if height[l] < height[r] {
246+ if height[l] < lMax {
247+ ans += lMax - height[l]
248+ } else {
249+ lMax = height[l]
250+ }
251+ l++
252+ } else {
253+ if height[r] < rMax {
254+ ans += rMax - height[r]
255+ } else {
256+ rMax = height[r]
257+ }
258+ r--
259+ }
260+ }
261+ return ans
262+ }
263+ ```
264+
265+ ``` php
266+ class Solution
267+ {
268+
269+ /**
270+ * @param Integer[] $height
271+ * @return Integer
272+ */
273+ function trap($height)
274+ {
275+ $n = count($height);
276+ if (!$n) return 0;
277+
278+ $l = 0;
279+ $l_max = $height[$l];
280+ $r = $n - 1;
281+ $r_max = $height[$r];
282+ $ans = 0;
283+ while ($l < $r) {
284+ if ($height[$l] < $height[$r]) {
285+ if ($height[$l] < $l_max) $ans += $l_max - $height[$l];
286+ else $l_max = $height[$l];
287+ $l++;
288+ } else {
289+ if ($height[$r] < $r_max) $ans += $r_max-$height[$r];
290+ else $r_max = $height[$r];
291+ $r--;
292+ }
293+ }
294+ return $ans;
295+ }
296+ }
297+ ```
298+
235299** 复杂度分析**
236300
237301- 时间复杂度:$O(N)$
You can’t perform that action at this time.
0 commit comments