原题地址:https://leetcode-cn.com/problems/container-with-most-water/description/
题目描述:
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。画 n 条垂直线,使得垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
注意:你不能倾斜容器,n 至少是2。
解题方法:
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int max = 0;
int max1 = 0;
for(int i = 0 ; i < n ; i ++){
if(height[i] <= max1) continue;
max1 = height[i];
int max2 = 0;
for(int j = n - 1 ; j > i; j --){
if(height[j] <= max2) continue;
max2 = height[j];
if(min(height[i], height[j]) * (j - i) > max)
max = min(height[i], height[j]) * (j - i);
}
}
return max;
}
};
自己用的方法比较low。。时间复杂度为o(n^2)。。。
学习:
int maxArea(vector<int>& height) {
if (height.size() < 2)
{
return 0;
}
int nLeft = 0;
int nRight = height.size() - 1;
int nMaxArea = 0;
while (nLeft < nRight)
{
int nLeftVal = height[nLeft];
int nRightVal = height[nRight];
int nVal = nLeftVal < nRightVal ? nLeftVal:nRightVal;
if (nMaxArea < nVal * (nRight - nLeft))
{
nMaxArea = nVal * (nRight - nLeft);
}
if (nLeftVal < nRightVal)
{
nLeft++;
}
else
{
nRight--;
}
}
return nMaxArea;
}
类似快排,采用双指针。指针移动的方式很单纯,不用想太多,在纸上画一画就明白了。。。
每次移动较小的指针,道理很好理解。