算法题-注水问题
问题:这些砖块之间能够注入多少水?
事实上主要分三部
1,取出这些砖块的最大高度和第二大高度
2。第二大高度乘上最大高度和第二大高度之间的距离。再减去中间的砖块,得出最大高度和第二大高度之间能够注入多少水
3。分别向最大高度和第二大高度之外的部分递归。得出最后的值
package com.test;
public class Test
{
static int result = 0; // 终于结果
static int[] wallHeights = new int[]
{1,6,1,2,3,4,100,1,9}; // 表示全部的墙的高度
public static void process(int start, int end)
{
// first:start和end之间最高的墙
// second:start和end之间第二高的墙
int first = 0, second = 0;
// firstIndex:第一高的墙在wallHeights中的索引
// secondIndex:第二高的墙在wallHeights中的索引
int firstIndex = 0, secondIndex = 0;
// 两堵墙必须至少有一堵墙的距离
if (end - start <= 1)
return;
// 開始获取第一高和第二高墙的砖数
// 冒泡
for (int i = start+1; i <= end; i++)
{
if(wallHeights[i]>wallHeights[secondIndex]){
if(wallHeights[i]>wallHeights[firstIndex])
{
//假设比第二大大又比第一大大,则i是第一大,第一大变成第二大
secondIndex = firstIndex;
firstIndex = i;
}
else
{
//假设比第二大大又比第一大小,则i是大二大。第一大不变
secondIndex = i;
}
}
}
first = wallHeights[firstIndex];
System.out.println("firstIndex "+firstIndex);
System.out.println("first "+first);
second = wallHeights[secondIndex];
System.out.println("secondIndex "+secondIndex);
System.out.println("second "+second);
// 获取左側墙的索引
int startIndex = Math.min(firstIndex, secondIndex);
// 获取右側墙的索引
int endIndex = Math.max(firstIndex, secondIndex);
// 计算距离
int distance = endIndex - startIndex;
// 假设第一高的墙和第二高的墙之间至少有一堵墙,那么開始计算这两堵墙之间能够放多少个单位的水
if (distance > 1)
{
result = result + (distance - 1) * second;
// 减去这两堵墙之间的砖数
for (int i = startIndex + 1; i < endIndex; i++)
{
result -= wallHeights[i];
}
}
// 開始递归处理左側墙距离開始位置能放多少水
process(start, startIndex);
// 開始递归处理右側墙距离结束位置能放多少水
process(endIndex, end);
}
public static void main(String[] args)
{
process(0, wallHeights.length - 1);
System.out.println(result);
}
}在此文章的基础上改的,中间部分不太明确,换成了自己的
http://blog.csdn.net/nokiaguy/article/details/14023225
浙公网安备 33010602011771号