给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
示例 1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例 2:
输入:height = [1,1]
输出:1
核心思路:
使用双指针,然后每次选择较短的那条边所对应的指针进行移动,因为移动较短的边有可能增加容器的高度,从而可能找到更大的容积(缩短宽度要增加高度)。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int maxArea(vector<int>& height)
{
// 定义双指针
int left = 0;
int right = height.size() - 1;
int maxArea = 0;
while (left < right)
{
int currArea = (right - left) * (min(height[left], height[right]));
maxArea = max(maxArea, currArea);
if (height[left] < height[right])
{
left++;
}
else
{
right--;
}
}
return maxArea;
}
};
int main()
{
Solution solution;
std::vector<int> height = { 1, 8, 6, 2, 5, 4, 8, 3, 7 };
int result = solution.maxArea(height);
std::cout << "最大容积为: " << result << std::endl;
return 0;
}