[LeetCode] 11. Container With Most Water 装最多水的容器

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 11. Container With Most Water 装最多水的容器相关的知识,希望对你有一定的参考价值。

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

42. Trapping Rain Water 类似,两条垂直的线和X轴组成一个容器,灌水多少不仅与两个柱子的高度有关,也与两个柱子的距离有关,公式:S(i,j) = min(ai, aj) * (j-i),容器不能倾斜,求容纳最多水的两个线组合。

用暴力搜索Brute Force, Time: O(n2)会超时。

使用双指针two pointers。 定义left,right两个指针,两指针相遇循环结束。何时移动左右指针呢,保留较高的柱子,移动较矮的柱子。

Time complexity: O(n),  Space complexity: O(1)

Java:

class Solution {
    public int maxArea(int[] height) {
        int l = 0;
        int r = height.length - 1;
        int ans = 0;
        while (l < r) {
            int h = Math.min(height[l], height[r]);
            ans = Math.max(ans, h * (r - l));
            if (height[l] < height[r])
                ++l;
            else
                --r;
        }
        return ans;
    }
}

Python:

class Solution:
    def maxArea(self, height):
        max_area, i, j = 0, 0, len(height) - 1
        while i < j:
            max_area = max(max_area, min(height[i], height[j]) * (j - i))
            if height[i] < height[j]:
                i += 1
            else:
                j -= 1
        return max_area  

 C++:

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

类似题目:

[LeetCode] 42. Trapping Rain Water 收集雨水

All LeetCode Questions List 题目汇总

 

以上是关于[LeetCode] 11. Container With Most Water 装最多水的容器的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode?????????python?????????11. Container With Most Water

LeetCode11. Container With Most Water 解题报告

leetcode_11. Container With Most Water

Leetcode 11. Container With Most Water (two pointers)

LeetCode 11. Container With Most Water

leetcode11 Container With Most Water