LeetCode刷题笔记 11. 盛最多水的容器

11. 盛最多水的容器

  • 题目要求
  • 题解
    • 自己的超蠢暴力法
    • 双指针法
    • 自己重写的双指针法
  • 参考链接

题目要求

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

说明:你不能倾斜容器,且 n 的值至少为 2。

LeetCode刷题笔记 11. 盛最多水的容器_第1张图片

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water

题解

自己的超蠢暴力法

看了下题目感觉好像可以做啊,就按最无脑的方式写了一下,贴上来是为了做数据对比。

#define min(a,b) ((a
class Solution {
public:
    int maxArea(vector<int>& height) {
        int i,j,k=0;
        for(i=0;i<height.size()-1;i++){
            for(j=i+1;j<height.size();j++){
                if(min(height[i],height[j])*(j-i)>k){
                    k=min(height[i],height[j])*(j-i);
                }                    
            }
        }
        return k;        
    }
};
执行用时 内存消耗
1788 ms 9.6 MB

双指针法

#include 
#include 
using namespace std;

class Solution
{
public:
    int maxArea(vector<int> &height)
    {
        int result = 0;
        int heightSize = int(height.size());
        int leftIndex = 0;
        int rightIndex = heightSize - 1;

        while (leftIndex != rightIndex)
        {
            int tmpHeight;
            int tmpWidth = rightIndex - leftIndex;
            //短的一侧向中间移动
            if (height[leftIndex] < height[rightIndex])
            {
                tmpHeight = height[leftIndex];
                leftIndex++;
            }
            else
            {
                tmpHeight = height[rightIndex];
                rightIndex--;
            }
            int tmpResult = tmpWidth * tmpHeight;
            if (tmpResult > result)
            {
                result = tmpResult;
            }
        }
        return result;
    }
};
执行用时 内存消耗
16 ms 9.8 MB

提升真的不是一点点,思路学习一下。
核心思路:

  1. 求最大面积的关注点应放在短的一边上
  2. 两边向中间收缩而不是遍历

自己重写的双指针法

这里我把初始result设为最初坐标下的值,原作者的写法不会漏掉最开始的情况是因为每次判断后会先把值保存起来再改坐标,而我的代码中并没有额外再保存中间值。

#define min(a,b) (a
class Solution {
public:
    int maxArea(vector<int>& height) {
        int s=height.size();
        int l=0,r=s-1;
        int width=r-l;
        int result=0,tmp=0;
        while(l!=r){
            tmp=min(height[l],height[r])*width;
            if(tmp>result)
                result=tmp;
            if(height[l]<height[r])
                l++;
            else 
                r--;
            width=r-l;
        }
        return result;        
    }
};
执行用时 内存消耗
16 ms 9.8 MB

参考链接

  • pinku-2 https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-cshi-xian-liang-chon/

你可能感兴趣的:(Leetcode)