Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

盛最多的水

来源Leetcode第11题盛最多的水

给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

用暴力法遍历时遇到了TLE的问题,重新考虑题目,不妨将两个指针设置在头和尾,取头尾指针中较小的*两指针之间的距离得到其之间的面积,因为面积是以较小的指针高度为准,所以移动较小的指针即可,直到两指针相遇。
严谨证明链接:双指针法正确性证明
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int maxArea(int* height, int heightSize){
int maxsize = 0;
int start = 0;
int end = heightSize-1;
int temp;
for(;start!=end;)
{
if(height[start]<height[end])
{
temp = (end - start)*(height[start]);
start++;
}
else
{
temp = (end - start)*(height[end]);
end--;
}
maxsize = (maxsize > temp?maxsize:temp);
}
return maxsize;
}