盛最多水的容器
题目链接:https://leetcode-cn.com/problems/container-with-most-water/submissions/
思路:双指针,从两端开始,每次把两个板中的短板向内移一格。因为向内的过程底长是单调递减的,而面积由短板决定,因此该搜索过程不会遗漏面积更大的情况。
参考代码:
class Solution {
public:
int maxArea(vector<int>& height) {
if (height.size() <= 1) {
return 0;
}
int left = 0;
int right = height.size() - 1;
int res = 0;
while (left < right) {
res = max(res, min(height[left], height[right]) * (right - left));
if (height[left] < height[right]) {
++left;
}
else {
--right;
}
}
return res;
}
};