思路:两边往中间扫,哪边高度小,哪边就是蓄水的瓶颈,需要往里移动。
/*
* @lc app=leetcode id=11 lang=cpp
*
* [11] Container With Most Water
*/
// @lc code=start
class Solution {
public:
int maxArea(vector<int>& height) {
int R = height.size()-1;
int L = 0;
int ans = 0;
while(L<R){
ans = max(ans,(R-L)*min(height[L],height[R]));
if(height[L] > height[R]){
R--;
}else{
L++;
}
}
return ans;
}
};
// @lc code=end
本文详细解析了LeetCode上一道经典算法题“盛最多水的容器”的解决方案。通过双指针从两端向中间扫描的方法,找出能盛放最多水的容器高度。此算法巧妙地利用了高度与宽度的关系,避免了暴力求解的复杂度。
834

被折叠的 条评论
为什么被折叠?



