每日一道算法题(20200304)积水问题优化

996 阅读1分钟

上一期的积水问题使用暴力求解 时间复杂度较高o(n^2);有优化空间

想法1:用空间换时间,分别从左到右和从右到左遍历数组,用两个数组记录遍历的结果(遍历过程中得到该位置的左边最高的柱子高度,或者得到右边最高的柱子高度);然后再用上一期的方法得到总的积水数;

再深入优化一下,用两个指针分别指向数组左右两边的的元素,两个指针做相向运动,左指针移动过程中,指针的最左边的最高的柱子高度是准确的,同理最右边的指针的右边的最高的柱子也是准确的,根据规则,如果左指针的左边最高的柱子矮于右指针的右边最高的柱子,则左指针的积水就可以计算出来,而同理,如果左指针的左边最高的柱子高于于右指针的右边最高的柱子,则右指针的积水可以计算出来;这样可以一次遍历得到积水数;结合代码来理解一下优化思路:

 private int getWaterTotal(int [] num) {

	int total = 0;
	int left = 1;
	int right = num.length-2;
	int leftMax = 0;
	int rignhtMax = 0;

	while (left <= right) {
		leftMax = Math.max(leftMax, num[left-1]);
		rignhtMax = Math.max(rignhtMax, num[right+1]);

		if (leftMax < rignhtMax) {
			if (leftMax > num[left]) {
				total = total + (leftMax - num[left]);
			}
			left ++;
		} else {
			if (rignhtMax > num[right]) {
				total = total + (rignhtMax - num[right]);

			}
			right --;
		}
	}
	return total;

}


写代码时候犯的错误:
1.left ++ 放在来最里层的if中;
2.while (left <= right)错误写为while (left < right);边界条件需要搞清楚