[Leetcode11]盛最多水的容器

给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

这题要一开始用很笨的方法解会报出超出时间限制,其实用动态规划去做会很快,先把挡板设置在左右两边,然后每次都判断左右两边挡板的高度去决定谁往中间移动,每次移动都判断容量的变化并存储最大的容量。

python:

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        if n < 2:
            return 0
        i = 0
        j = n-1
        maxArea = 0
        while i != j:
            if height[i] <= height[j]:
                h = height[i]
                if h * (j-i) > maxArea:
                    maxArea = h * (j-i)
                i += 1
            else:
                h = height[j]
                if h * (j-i) > maxArea:
                    maxArea = h * (j-i)
                j -= 1
            
        return maxArea

C++: 

class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        if(n < 2) return 0;
        int i = 0;int j = n-1;int h = 0;
        int maxArea = 0;
        while(i != j){
            if(height[i] <= height[j]){
                h = height[i];
                if((h * (j - i)) > maxArea) maxArea = (h * (j - i));
                i += 1;
            }
            else{
                h = height[j];
                if((h * (j - i)) > maxArea) maxArea = (h * (j - i));
                j -= 1;
            }
        }
        return maxArea;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/82894838