Loading

盛最多水的容器

盛最多水的容器

作者:Grey

原文地址:

博客园:盛最多水的容器

CSDN:盛最多水的容器

题目描述

LeetCode 11. Container With Most Water

思路

使用双指针,设置两个指针,假设数组长度为len

左指针l0位置开始,右指针rlen-1开始,

height[l]height[r]无非有如下几种情况:

// 情况1
height[r] < height[l]
// 情况2
height[r] == height[l]
// 情况3
height[r] > height[l]

对于情况1,我们可以这样考虑,不管区间l...r之间的值有哪些,我至少可以确保如果横线划在height[r]位置,可以收获

(r - l) * height[r]

如下示意图

image

这么多雨水,然后r指针向右移动。

情况3同理,不管l...r之间的值有哪些,我至少可以确保如果横线划在height[l]位置,可以收获

(r - l) * height[l]

如下示意图

image

这么多雨水,然后l指针向左移动。

对于情况2,其实也可以归结到上面任何一种情况中,假设我归结在情况3中,那么对于情况2和情况3,统一可以获得的最大雨水量是:

(r - l) * height[l]

然后l指针向左移动。

结束的条件是当lr相等的时候,每一次移动l或者r都收集一遍,并且和最大值max比较,最后返回max的值即可。

整个算法的时间复杂度是O(N),空间复杂度是O(1)

完整代码

    public static int maxArea(int[] heights) {
        if (null == heights || heights.length == 1) {
            return 0;
        }
        int l = 0;
        int r = heights.length - 1;
        int w;
        int max = 0;
        while (l < r) {
            if (heights[r] < heights[l]) {
                w = (r - l) * heights[r];
                r--;
            } else {
                w = (r - l) * heights[l];
                l++;
            }
            max = Math.max(max, w);
        }
        return max;
    }

更多

算法和数据结构笔记

posted @ 2016-09-28 22:30  Grey Zeng  阅读(658)  评论(0编辑  收藏  举报