用双指针遍历height数组的左右两端,对于相对短的一边就移动(木桶效应),并不断更新答案。
python
classSolution(object):defmaxArea(self,height):""" :type height: List[int] :rtype: int """left,right=0,len(height)-1res=0whileleft<right:res=max(res,(right-left)*min(height[left],height[right]))ifheight[left]<=height[right]:left+=1else:right-=1returnresc++
classSolution{public:intmaxArea(vector<int>&height){// 数组的双指针一般都是首尾指针// 根据木桶效应,容器的接水量受短边制约,所以每次移动短边的指针intn=height.size();intleft=0,right=n-1;intres=0;while(left<right){res=max(res,(right-left)*min(height[left],height[right]));if(height[left]<height[right]){left++;}else{right--;}}returnres;}};