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

心已入冬 提交于 2020-05-08 03:38:38

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 题目汇总

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!