-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolumeOfHistogramLcci.java
More file actions
85 lines (79 loc) · 2.64 KB
/
VolumeOfHistogramLcci.java
File metadata and controls
85 lines (79 loc) · 2.64 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package leetcode;
/**
* VolumeOfHistogramLcci
* https://leetcode-cn.com/problems/volume-of-histogram-lcci/
* 面试题 17.21. 直方图的水量
* https://leetcode-cn.com/problems/volume-of-histogram-lcci/solution/sao-miao-xian-jie-ti-xiao-lu-bu-gao-by-o-dhe0/
*
* @since 2021-04-02
*/
public class VolumeOfHistogramLcci {
public static void main(String[] args) {
VolumeOfHistogramLcci sol = new VolumeOfHistogramLcci();
System.out.println(sol.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
System.out.println(sol.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 1, 1}));
System.out.println(sol.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 1, 2, 1, 0, 1}));
System.out.println(sol.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 0, 2, 1, 0, 1}));
System.out.println(sol.trap(new int[]{4, 2, 3}));
System.out.println(sol.trap(new int[]{}));
System.out.println(sol.trap(new int[]{0}));
}
public int trap(int[] height) {
int total = 0;
while (true) {
int lastStart = -1;
for (int i = 0; i < height.length; i++) {
if (height[i] > 0) {
if (lastStart >= 0) {
total += (i - lastStart - 1);
}
lastStart = i;
height[i]--;
}
}
if (lastStart == -1) {
break;
}
}
return total;
}
public int trap_2(int[] height) {
if (height == null || height.length < 1) { // [] fail
return 0;
}
int lastTotal = -1;
int total = 0;
while (total == 0 || lastTotal != total) { // 4, 2, 3 fail
lastTotal = total;
int lastStart = -1;
for (int i = 0; i < height.length; i++) {
if (height[i] > 0) {
if (lastStart >= 0) {
total += (i - lastStart - 1);
}
lastStart = i;
height[i]--;
}
}
}
return total;
}
public int trap_1(int[] height) {
int lastTotal = -1;
int total = 0;
while (lastTotal != total) { // 4, 2, 3 fail
lastTotal = total;
int lastStart = -1;
for (int i = 0; i < height.length; i++) {
if (height[i] > 0) {
if (lastStart >= 0) {
total += (i - lastStart - 1);
}
lastStart = i;
height[i]--;
}
}
}
return total;
}
}