LeetCode 42. 接雨水
题目描述
✅ 42. 接雨水
思路分析
双指针
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func trap(height []int) int {
left, right := 0, len(height)-1
leftMax, rightMax := 0, 0
res := 0
for left < right {
if height[left] < height[right] {
if height[left] >= leftMax {
leftMax = height[left]
} else {
res += leftMax - height[left]
}
left++
} else {
if height[right] >= rightMax {
rightMax = height[right]
} else {
res += rightMax - height[right]
}
right--
}
}
return res
}
- 时间复杂度:O (n),其中 n 是数组的长度。
- 空间复杂度:O (1),只使用了常数级别的额外空间。
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用