看到這麼一個題,覺得挺有意思的,原文鏈接 http://blog.jobbole.com/50705/
如上圖,有不同高度的牆。
這個圖片由一個整數數組所代表,數組中每個數是牆的高度。表示爲數組[2,7,3,1,5,3]
以1×1的方塊爲單位計算容積。假如開始下雨了,那麼牆之間的水坑能夠裝多少水呢?
思路:
積水的常識:兩邊高,中間低纔會積水,積水的深度取決於較低的那個邊。
方法1: 先找到最高的牆,最左邊到最高的牆之間,只要有左牆>右牆的情況,便可和最高強形成積水,最右邊同理;
[2,7,3,1,5,3],最大值下標爲1;
1的左邊,2小於7,顯然不能裝水,waterLeft=0;
然後從最右邊遍歷,index=5,max=3;
index=4,a[4]>max ,max=5;
index=3, a[3]<max, waterRight=waterRight+max-a[3]=0+5-1=4;
index=2, a[2]<max,waterRight=waterRight+max-a[2]=4+5-3=6;
此方法遍歷次數爲2;
方法2:方法1是從中間至兩邊,該方法是從兩邊到中間,右牆高於左牆,則以右牆爲基準,從左邊遍歷,如果存在左牆>右牆的情況,則能積水,反之同理;
<span style="white-space:pre"> </span>public static int waterCalculation(int[] wall){
int pLeft=0;
int pRight=wall.length-1;
int maxLeft=wall[pLeft];//左側最高牆
int maxRight=wall[pRight];//右側最高牆
int pool=0;//積水
while(pLeft<pRight){
if(maxLeft<maxRight){//如果右側牆高一些,則以該牆爲最高牆,並從左側尋找左牆>右牆的情況
pLeft=pLeft+1;
if(wall[pLeft]>=maxLeft){//
maxLeft=wall[pLeft];
}else{
pool=pool+maxLeft-wall[pLeft];
}
}else{
pRight=pRight-1;
if(wall[pRight]>=maxRight){//
maxRight=wall[pRight];
}else{
pool=pool+maxRight-wall[pRight];
}
}
}
return pool;
}
<span style="white-space:pre"> </span>public static void main(String[] args){
int[] a={2,7,3,1,5};
System.out.println(Arrays.toString(a)+"的積水爲:"+WaterCalculation.waterCalculation(a));
int[] b={2,5,1,2,3,4,7,6};
System.out.println(Arrays.toString(b)+"的積水爲:"+WaterCalculation.waterCalculation(b));
int[] c={2,5,1,3,1,2,1,7,7,6};
System.out.println(Arrays.toString(c)+"的積水爲:"+WaterCalculation.waterCalculation(c));
}
[2, 7, 3, 1, 5]的積水爲:6
[2, 5, 1, 2, 3, 4, 7, 6]的積水爲:10
[2, 5, 1, 3, 1, 2, 1, 7, 7, 6]的積水爲:17