Leetcode刷题37-11.盛最多水的容器(C++详细解法!!!)

题目来源:链接: [https://leetcode-cn.com/problems/container-with-most-water/].

11.盛最多水的容器

  • 1.问题描述
  • 2.我的解决方案
  • 3.大神们的解决方案
  • 4.我的收获

1.问题描述

给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
Leetcode刷题37-11.盛最多水的容器(C++详细解法!!!)_第1张图片
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

2.我的解决方案

方法1. 我用的暴力解决法(但是差点超时)。。。(代码在本节)
方法2. 动态规划方法。首先定义两个 指针。分别指向 首尾。

  1. 这题可以类比为求最大面积(以短边为宽或长)。
  2. 想要面积最大,肯定是长宽都长才好,我们先占住一个,让长最长(也就是从数组首尾开始算)。
  3. 题目要求 :求面积时,要取 指针 较小对应 的那个值。
  4. 因为求面积最大,肯定是 较小的那个指针 拖后腿了,这时我们移动较小的那个指针,再次求出面积,与刚才的那个对比,取较大的那个。
  5. 重复直到 left < right 不成立。(代码见第三节 大神的解决方案)
    代码如下:
class Solution {
public:
    int maxArea(vector<int>& height) {
        int tmp = 0, res = 0, max = 0;
        for(int i = 0; i < height.size(); ++i)
        {
            for(int j = i + 1; j < height.size(); ++j)
            {
                if(height[i] < height[j])
                {
                    tmp = height[i];
                }
                else
                {
                    tmp = height[j];
                }
                res = tmp*(j - i);
                if(res > max)
                {
                    max = res;
                }
            }
        }
        return max;
    }
};

3.大神们的解决方案

动态规划方法(说的这么高大上,其实就是定义两个辅助指针变量):

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

4.我的收获

暴力解决法虽然好但是。。。超时啊

2019/3/27 胡云层 于南京 37

你可能感兴趣的:(LeetCode从零开始)