Container With Most Water 双指针法

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

双指针

一种枚举算法的优化,在具有有序性质的问题上可以优化复杂度,此题题意是在数组中选取两条边和X轴一起组成矩形容器,最多能存储多少水,影响容量的因素有两个: 容器的底(左右两条线段长度之差)和高(左右两条线段长度最小值)。
双指针在数组首尾相向移动, 优化掉大部分的无效计算([3,1,3,3] 这个数组,左右指针分别在首尾,左边的指针向右移动,底和高都会减少,面积显然不会增大,这一步计算可以直接优化掉)

class Solution {
public:
    int maxArea(vector<int>& height) {
        int ans = 0, l = 0, r = height.size() - 1;
        if(!height.empty()) {
            ans = max(ans, (r - l) * min(height[l], height[r]));
            while(l < r){
                if(height[l] < height[r]){
                    while(l < r && height[l+1] < height[l]){
                        l++;
                    }
                    l++;
                }
                else {
                    while(l < r && height[r - 1] < height[r]){
                        r--;
                    }
                    r--;
                }
                ans = max(ans, (r - l) * min(height[l], height[r]));
            }
            
        }
        return ans;
    }
};

原文地址:https://www.cnblogs.com/joeylee97/p/9165782.html