forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrappingRainWater.java
62 lines (58 loc) · 1.77 KB
/
TrappingRainWater.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//Version 0: Two pointer
public class Solution {
/**
* @param heights: an array of integers
* @return: a integer
*/
public int trapRainWater(int[] heights) {
// write your code here
int left = 0, right = heights.length - 1;
int res = 0;
if(left >= right)
return res;
int leftheight = heights[left];
int rightheight = heights[right];
while(left < right) {
if(leftheight < rightheight) {
left ++;
if(leftheight > heights[left]) {
res += (leftheight - heights[left]);
} else {
leftheight = heights[left];
}
} else {
right --;
if(rightheight > heights[right]) {
res += (rightheight - heights[right]);
} else {
rightheight = heights[right];
}
}
}
return res;
}
}
// Version 1
public class Solution {
/**
* @param heights: an array of integers
* @return: a integer
*/
public int trapRainWater(int[] heights) {
if (heights.length == 0) {
return 0;
}
int[] maxHeights = new int[heights.length + 1];
maxHeights[0] = 0;
for (int i = 0; i < heights.length; i++) {
maxHeights[i + 1] = Math.max(maxHeights[i], heights[i]);
}
int max = 0, area = 0;
for (int i = heights.length - 1; i >= 0; i--) {
area += Math.min(max, maxHeights[i]) > heights[i]
? Math.min(max, maxHeights[i]) - heights[i]
: 0;
max = Math.max(max, heights[i]);
}
return area;
}