Skip to content

Commit aaa7a98

Browse files
committed
solve 42.trapping-rain-water using two pointers
1 parent fb52b86 commit aaa7a98

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

vscode/42.trapping-rain-water.1.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* @lc app=leetcode id=42 lang=java
3+
*
4+
* [42] Trapping Rain Water
5+
*
6+
* https://leetcode.com/problems/trapping-rain-water/description/
7+
*
8+
* algorithms
9+
* Hard (44.33%)
10+
* Likes: 4310
11+
* Dislikes: 80
12+
* Total Accepted: 339.3K
13+
* Total Submissions: 761.1K
14+
* Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
15+
*
16+
* Given n non-negative integers representing an elevation map where the width
17+
* of each bar is 1, compute how much water it is able to trap after raining.
18+
*
19+
*
20+
* The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
21+
* In this case, 6 units of rain water (blue section) are being trapped. Thanks
22+
* Marcos for contributing this image!
23+
*
24+
* Example:
25+
*
26+
*
27+
* Input: [0,1,0,2,1,0,1,3,2,1,2,1]
28+
* Output: 6
29+
*
30+
*/
31+
class Solution {
32+
public int trap(int[] height) {
33+
int n = height.length;
34+
if (n <= 1) {
35+
return 0;
36+
}
37+
38+
int left = 0;
39+
int right = n - 1;
40+
int leftMax = height[left];
41+
int rightMax = height[right];
42+
43+
int res = 0;
44+
while (left <= right) {
45+
leftMax = Math.max(leftMax, height[left]);
46+
rightMax = Math.max(rightMax, height[right]);
47+
if (leftMax < rightMax) {
48+
res += leftMax - height[left];
49+
left++;
50+
} else {
51+
res += rightMax - height[right];
52+
right--;
53+
}
54+
}
55+
56+
return res;
57+
}
58+
}
59+

0 commit comments

Comments
 (0)