-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_42TrappingRainWater.java
43 lines (38 loc) · 1.43 KB
/
_42TrappingRainWater.java
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
package com.test.leetcode;
class _42TrappingRainWater {
public static int trap(int[] height) {
int[][] stackk = new int[height.length+1][2];
int top = 0;
int vol = 0;
for (int i=0; i<height.length; i++) {
//System.out.println("i="+i);
if (top==0 || stackk[top-1][0]>height[i]) {
stackk[top][0] = height[i];
stackk[top][1] = i;
top++;
} else {
int max = stackk[top-1][0];
while (top>0 && stackk[top-1][0]<=height[i]) {
//System.out.println("max="+max+" stack[last]="+stackk[top-1][0]);
if (stackk[top-1][0]>max) {
vol += (i-stackk[top-1][1]-1) * (stackk[top-1][0]-max);
max = stackk[top-1][0];
}
top--;
}
if (top>0 && stackk[top-1][0]>height[i]) vol += (i-1-stackk[top-1][1]) * (height[i]-max);
stackk[top][0] = height[i];
stackk[top][1] = i;
top++;
}
for(int j=0; j<top; j++) System.out.println("stack["+j+"]="+stackk[j][0]+" i="+stackk[j][1]);
//System.out.println("vol="+vol);
}
return vol;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] height = {0,3,1,2,4,1,0,2};
System.out.println(trap(height));
}
}