接雨水
# 接雨水 (opens new window)
Category | Difficulty | Likes | Dislikes |
---|---|---|---|
algorithms | Hard (63.24%) | 5001 | - |
Tags
Companies
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 1:
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
1
2
3
2
3
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
1
2
2
提示:
- n == height.length
- 1 <= n <= 2 * 104
- 0 <= height[i] <= 105
Discussion (opens new window) | Solution (opens new window)
# 代码
/*
* @Author: 仲灏<izhaong@outlook.com>🌶🌶🌶
* @Date: 2024-02-06 12:36:21
* @LastEditTime: 2024-02-06 13:11:52
* @LastEditors: 仲灏<izhaong@outlook.com>🌶🌶🌶
* @Description:
* @FilePath: /leetcode/42.接雨水.js
*/
/*
* @lc app=leetcode.cn id=42 lang=javascript
*
* [42] 接雨水
*
* https://leetcode.cn/problems/trapping-rain-water/description/
*
* algorithms
* Hard (63.24%)
* Likes: 5001
* Dislikes: 0
* Total Accepted: 856.9K
* Total Submissions: 1.4M
* Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
*
* 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
*
*
*
* 示例 1:
*
*
*
*
* 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出:6
* 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
*
*
* 示例 2:
*
*
* 输入:height = [4,2,0,3,2,5]
* 输出:9
*
*
*
*
* 提示:
*
*
* n == height.length
* 1 <= n <= 2 * 10^4
* 0 <= height[i] <= 10^5
*
*
*/
// @lc code=start
/**
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
let area = 0
const stack = []
for (let i = 0; i < height.length; i++) {
while (stack.length && height[i] >= height[stack[stack.length - 1]]) {
const bh = height[stack.pop()]
if (!stack.length) {
break;
}
const end = stack[stack.length - 1]
const ca = (Math.min(height[end], height[i]) - bh) * (i - end - 1)
area += ca
}
stack.push(i)
}
return area
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = trap;
// @after-stub-for-debug-end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
上次更新: 2024/04/08, 16:26:17