leetcode11

解题思路:

步骤1. left指向最左边的红点(left=0),right指向最后边的红点(right=height.size()-1),此时能装水的高度是 min(height[left], height[right]), 装水的宽度是 right-left.计算当前能装水的容量 和 之前最大值进行比较,即 res

步骤2. left和right更新策略,谁短谁更新。更新left,即left++,更新right,即right--;

步骤3. 只要left < right 重复步骤1和步骤2;

class Solution {

public:

    int maxArea(vector<int>& height) {

        

        int left = 0;

        int right = height.size() - 1;//设立左右起始点

        int ans = 0;

        

        while(left < right) {

            

            int curAns = min(height[left], height[right]) * (right - left);//记录目前的储水值

            ans = max(ans, curAns);//更新结果,保持全局最大值

            

            if(height[left] > height[right])//移动左右高度

                right --;

            else

                left ++;

        }

        

        return ans;

    }

};
 

猜你喜欢

转载自blog.csdn.net/hua111hua/article/details/83053282