Leetcode在线编程 container-with-most-water
题目链接
题目描述
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.
题意
x轴正方向上,有长度不等的垂直于X轴的线段,现找出与X轴围起来面积最大的那对线段。
解题思路
2条线段与x轴围起来的面积,决定因素是短的那条
先取头尾两条线段i,j
如果h[i]
AC代码
class Solution {
public:
int maxArea(vector<int> &height) {
int i = 0 , j = height.size()-1;
int Max = 0;
while(i<j)
{
int tmp;
if(height[i] < height[j])
{
tmp = (j-i)*height[i];
i++;
}
else
{
tmp = (j-i)*height[j];
j--;
}
Max = max(Max,tmp);
}
return Max;
}
};