Leetcode 42.接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
在这里插入图片描述
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

解法1:对于位置i, 能存储的雨水取决于向左扫描以及向右扫描中最大高度的较小的一个,开两个数组存储向左扫描以及向右扫描的最大高度。时间复杂度,空间复杂度均为O(n)

int max(int x,int y) {
	return x>y? x:y;
}

int min(int x,int y) {
	return x<y? x:y;
}

int trap(int* height, int heightSize){
	if(height==NULL||heightSize<=0) {
		return 0;
	}
	int water=0;
	int left[heightSize];
	int right[heightSize];
	left[0]=height[0];
	right[heightSize-1]=height[heightSize-1];
	// 位置i向左扫描的高度最大值
	for (int i = 1; i < heightSize; i++)
	{
		left[i]=max(left[i-1],height[i]);
	}
	// 位置i向右扫描的高度最大值
	for (int i = heightSize-2; i >=0; i--)
	{
		right[i]=max(right[i+1],height[i]);
	}
	for (int i = 0; i < heightSize; i++)
	{
		water+=min(left[i],right[i])-height[i];
	}
	return water;
}

解法2:双指针法,时间复杂度O(n), 空间复杂度O(1)

int trap(int* height, int heightSize){
	int water=0;
	int left_index = 0;
	int right_index = heightSize-1;
	int left_max=0,right_max=0;
	while(left_index<right_index) {
		if(height[left_index]<height[right_index]) {
			if(height[left_index]>left_max) {
				left_max=height[left_index];
			} else {
				water+=left_max-height[left_index];
			}
			left_index++;
		} else {
			if(height[right_index]>right_max) {
				right_max=height[right_index];
			} else {
				water+=right_max-height[right_index];
			}
			right_index--;
		}
	}
	return water;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章