LeetCode 11题 盛最多水的容器
题目描述:给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
我脑子有些容易卡壳。尤其在这道题目上。
捋了捋思路。可以把储水量理解成面积S。
-
这个面积怎么算? 是两条边中最短的那条边乘以x轴上的长度。
-
x轴长度最长是什么时候?就是当我选取的两条线分别是height数组的第一位和最后一位的时候。
-
ok了,上面的这个作为初始条件。用双指针分别指在两头,从两边往中间(中间这个词不太准确,这两个指针需要一直走直到相遇)找可能的最大面积。
-
那么怎么决定这两个指针谁移动呢?
- 上面第一点中,计算面积使用的height值是两个里面最小的那个,可以说小值使我们计算面积受限。这样的话我的两个指针里指向大height值的那个指针就不需要动,让指向小值的指针前进一格即可。
- 计算面积,保留最大面积值,然后对现在的两个指针,重复上一步。
int shortLine(lh, rh){
if(lh > rh) return rh;
else return lh;
}
int cacuSpace(lh, rh, len){
return shortLine(lh, rh)*len;
}
int maxArea(int* height, int heightSize){
// cacu the space,and move the short line
int lpIdx = 0;
int rpIdx = heightSize - 1;
int space = cacuSpace(height[0], height[heightSize - 1], heightSize - 1);
while(rpIdx > lpIdx){
if(height[lpIdx] > height[rpIdx]){
rpIdx --;
}
else lpIdx ++;
int tmpspace = cacuSpace(height[lpIdx], height[rpIdx], rpIdx-lpIdx);
if(tmpspace > space) space = tmpspace;
}
return space;
}