Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
l
和 r
,盛水容量为 (r - l) * min(height[l], height[r])
,每次右移 l
或左移 r
(移动的应该是高度更小的那个,比如如果 height[l]
大,右移 l
乘积肯定缩小)来缩小范围,时间复杂度 O(n)
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int l = 0;
int r = size(height) - 1;
while (l != r) {
if (height[l] < height[r]) {
res = max(res, (r - l) * height[l]);
++l;
} else {
res = max(res, (r - l) * height[r]);
--r;
}
}
return res;
}
};