每日一道算法题(202020303):积水问题

265 阅读1分钟

暴力解法: 考虑每一个柱子上可以接多少水?着取决于在它左右两边的所有柱子, 左右两边分别找到各自的最高的柱子,如果找到的两个柱子中的最矮的柱子比当前柱子高,则当前柱子会积水(两个柱子中的最矮的柱子的高度-当前柱子高度),否则不会积水

public int getWaterTotal(int [] height) {

	if (height == null || height.length < 3) {
		return 0;
	}

	int total = 0;
	for (int k = 0; k < height.length; k++) {
		int leftMax = 0;
		for (int i = k-1; i >=0; i--) {
			leftMax = Math.max(leftMax, height[i]);
		}
		int rightMax = 0;
		for (int j = k + 1; j < height.length; j++) {
			rightMax = Math.max(rightMax, height[j]);
		}

		//分两种情况考虑:1.leftMax和rightMax中的最小的>height[k];
		// 2.leftMax和rightMax中的最小的=<height[k];
		if (Math.min(leftMax,rightMax) > height[k]) {
			total = total + (Math.min(leftMax,rightMax) -height[k]);
		}
		if (Math.min(leftMax,rightMax) > height[k]) {
			//不会积水
		}
	}
	return total;
}

优化算法在下一期进行(动态规划)