class Solution { public: int maxArea(vector<int>& height) { //双指针法:从最宽的容器开始计算,当更窄的容器盛水量要大于之前容器,那必须比之前容器高,因此可以移动两个指针,直到最窄time O(n),space O(1); int low=0; int high=height.size()-1; int volume=0; while(low<high){ int h=min(height[low],height[high]); volume=max(volume,h*(high-low)); if(height[low]<height[high]){ low++; while(low<high && height[low]<=h) ++low; }else{ high--; while(low<high && height[high]<=h) --high; } } return volume; } };
原文地址:https://www.cnblogs.com/joelwang/p/11007993.html
时间: 2024-11-05 21:59:56