LeetCode 热题 100 总结——盛水最多的容器

58 阅读1分钟

思路 定义左右两个双指针,使两个指针指向的地方为容器的边界,不同于暴力解法的地方在于,使用双指针法,每当让height值小的那个指针往height值高的那个方向移动时,此时height值所处的位置不再是容器的边界。

解题方法 描述你的解题方法 原因: 假设左右指针的值为xy(x<y),而距离为t,此时容量为xt: 当右指针往左移动时,容量都不会大于这个xt了,因为移动的时候t会变小,而因为短板效应,高度始终为x,容量是一直减小,这个左指针作为边界的最大值已经找到了

public:
    int maxArea(vector<int>& height) {
        int len = height.size();
        // i,j : 将指针指向数组两侧
        int i = 0;
        int j = len - 1;
        // res 计算出此时的储水量
        int res = std::min(height[i], height[j]) * (j - i);
        // 给出扫描停止条件:i=j
        while (i < j) {
            // 找出较小的高度,将对应指针向内侧移动,直到找出大于原来高度的
            if (height[i] <= height[j]) {
                int temp = i;
                while (height[i] <= height[temp] && i < j) {
                    i++;
                }
                res = std::max(res, std::min(height[i], height[j]) * (j - i));
            } else {
                int temp = j;
                while (height[j] <= height[temp] && i < j) {
                    j--;
                }
                res = std::max(res, std::min(height[i], height[j]) * (j - i));
            }
        }
        return res;
    }
};

作者:JiaPeng Cai 链接:leetcode.cn/problems/co… 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。