当青训营遇上码上掘金
主题描述
接青豆问题(实际上即为leetcode中的接雨水问题)
- 现有 n 个宽度为 1 的柱子,给出 n 个非负整数依次表示柱子的高度,排列后如下图所示,此时均匀从上空向下撒青豆,计算按此排列的柱子能接住多少青豆。(不考虑边角堆积)
以下为上图例子的解析:
输入:height = [5,0,2,1,4,0,1,0,3]
输出:17
解析:上面是由数组 [5,0,2,1,4,0,1,0,3] 表示的柱子高度,在这种情况下,可以接 17 个单位的青豆。
思路解析
-
本题实际上是leetcode上接雨水的题目
-
这里我们可以使用单调栈的方式来解题,详见leetcode
-
如果使用不同的思路,首先找到总的面积,再减去柱子本身的面积结果即为水滴的面积
-
找出最高的柱子的位置,然后从左边遍历求出到最高柱子的总面积,
-
然后从右边遍历求出到最高柱子的总面积,在减去柱子的面积就等于水滴的面积
具体代码
public class trap42 {
public static void main(String[] args) {
System.out.println(new trap42().trap(new int[]{5,0,2,1,4,0,1,0,3}));
}
public int trap(int[] height) {
if(height==null||height.length==0){
return 0;
}
int maxHeightIndex = 0;
int maxHeight = height[0];
for (int i = 1; i < height.length; i++) {
if(height[i]>maxHeight){
maxHeight = height[i];
maxHeightIndex = i;
}
}
int pillarSum = 0;
int totalSum = 0;
int currentMaxHeight = 0;
for (int i = 0; i <= maxHeightIndex; i++) {
int currentPillar = height[i];
if(currentPillar>currentMaxHeight){
totalSum += currentPillar;
currentMaxHeight = currentPillar;
}else {
totalSum += currentMaxHeight;
}
pillarSum += currentPillar;
}
currentMaxHeight = 0;
for (int i = height.length-1; i > maxHeightIndex; i--) {
int currentPillar = height[i];
if(currentPillar>currentMaxHeight){
totalSum += currentPillar;
currentMaxHeight = currentPillar;
}else {
totalSum += currentMaxHeight;
}
pillarSum += currentPillar;
}
return totalSum-pillarSum;
}
}