Skip to content

Commit 20e5749

Browse files
author
谢育欣
committed
done
1 parent c66fb1b commit 20e5749

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/com/leetcode/Main42.java

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* 42. 接雨水
77
*/
88
public class Main42 {
9-
public int trap(int[] height) {
9+
public int trapDandiaoZhan(int[] height) {
1010
int sum = 0;
1111
Stack<Integer> stack = new Stack<>();
1212
int current = 0;
@@ -27,4 +27,32 @@ public int trap(int[] height) {
2727
}
2828
return sum;
2929
}
30+
31+
public int trapDoubleCurser(int[] height) {
32+
int left = 0;
33+
int right = height.length - 1;
34+
int res = 0;
35+
int leftMax = 0;
36+
int rightMax = 0;
37+
while (left != right) {
38+
leftMax = Math.max(leftMax, height[left]);
39+
rightMax = Math.max(rightMax, height[right]);
40+
if (leftMax < rightMax) {
41+
// 可以放心计算左指针所在柱子的雨水量
42+
res += leftMax - height[left];
43+
left += 1;
44+
} else {
45+
// 可以放心计算右指针所在柱子的雨水量
46+
res += rightMax - height[right];
47+
right -= 1;
48+
}
49+
}
50+
return res;
51+
}
52+
53+
public static void main(String[] args) {
54+
int[] req = {4,2,0,3,2,5};
55+
Main42 main42 = new Main42();
56+
System.out.println(main42.trapDoubleCurser(req));
57+
}
3058
}

0 commit comments

Comments
 (0)