Skip to content

Commit d10cba5

Browse files
committed
ok
1 parent e76c4ad commit d10cba5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/com/leetcode/Main42.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.leetcode;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* 42. 接雨水
7+
*/
8+
public class Main42 {
9+
public int trap(int[] height) {
10+
int sum = 0;
11+
Stack<Integer> stack = new Stack<>();
12+
int current = 0;
13+
while (current < height.length) {
14+
//如果栈不空并且当前指向的高度大于栈顶高度就一直循环
15+
while (!stack.empty() && height[current] > height[stack.peek()]) {
16+
int h = height[stack.peek()]; //取出要出栈的元素
17+
stack.pop(); //出栈
18+
if (stack.empty()) { // 栈空就出去
19+
break;
20+
}
21+
int distance = current - stack.peek() - 1; //两堵墙之前的距离。
22+
int min = Math.min(height[stack.peek()], height[current]);
23+
sum = sum + distance * (min - h);
24+
}
25+
stack.push(current); //当前指向的墙入栈
26+
current++; //指针后移
27+
}
28+
return sum;
29+
}
30+
}

0 commit comments

Comments
 (0)