题目:https://leetcode.cn/problems/container-with-most-water/description/
暴力求解会超时。经典不看答案不会写系列。双指针可以解决问题,思想很巧妙:
- low指针从0开始,high指针从尾部开始
- 计算
[low,high]
的面积,找出更短木板的一侧,向内侧移动,因为这样面积才可能会变大,如果移动更高木板的一侧, 面积必定不会变大。
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int maxS = 0;
int low = 0, high = len - 1;
while (low < high) {
int s = (high - low) * min(height[low], height[high]);
maxS = max(s, maxS);
if (height[low] <= height[high]) {
low++;
}
else {
high--;
}
}
return maxS;
}
};