暴力O(n^2),但是可以通过一些“剪枝”使其达到O(n),但是证明是一个问题。
We starts with the widest container, l = 0 and r = n - 1. Let's say the left one is shorter: h[l] < h[r]. Then, this is already the largest container the left one can form. There's no need to consider it again. Therefore, we just throw it away and start again with l = 1 and r = n -1.
class Solution { public: int maxArea(vector<int>& height) { int r=height.size()-1,l=0,max=0; while(l<r){ max=(max>min(height[l],height[r])*(r-l))?max:min(height[l],height[r])*(r-l); if (height[l]>height[r]) r--; else l++; } return max; } };
本文深入探讨了求解最大盛水量的算法问题,通过双指针技术实现O(n)复杂度的解决方案,避免了传统的O(n^2)暴力搜索。文章详细解释了算法思路,即从两端开始向中间逼近,每次移动高度较低的一侧指针,直至找到最大盛水量。
1106

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



