Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
给定
n
个非负的整数
a1
,
a2
, …,
an
,(
i
,
ai
) and (
i
, 0)分别代表座标(
i
,
ai
)。连接(
i
,
ai
) and (
i
, 0)画直线,共有
n
条。找出两条直线,使得两条直线与x轴形成的容器能够盛最多的水。
一般都会想到两个for循环,但时间复杂度肯定不符合要求。 思路:从两端开始算起,谁的高度小就往该方向++或者–,记录最大面积,直到两个索引相遇。
C++:
int Solution::maxArea(vector<int> &height) {
int length = height.size();
int i = 0, j = length - 1;
int maxArea = 0;
int temp = 0;
while(i < j){
if(height[i] > height[j]){
temp = height[j] * (j - i);
j--;
} else if(height[i] < height[j]){
temp = height[i] * (j - i);
i++;
} else if(height[i] == height[j]){
temp = height[i] * (j - i);
i++;
j--;
}
maxArea = temp > maxArea ? temp : maxArea;
}
return maxArea;
}