力扣刷题:11. 盛最多水的容器

题目要求

在这里插入图片描述
在这里插入图片描述

版本一:凭借我的直觉但是超时的做法

class Solution {
    
    
public:
    int maxArea(vector<int>& height) {
    
    
        unsigned MaxArea = 0, beforeHeight = 0, lowerHeight;
        for (unsigned i = 0; i < height.size(); i++)
        {
    
    
            if (height.at(i) <= beforeHeight)
            {
    
    
                continue;
            }
            beforeHeight = height.at(i);
            for (unsigned j = i+1; j < height.size(); j++)
            {
    
    
                lowerHeight = std::min(height.at(i), height.at(j));
                MaxArea = std::max(lowerHeight * (j - i), MaxArea);
            }
        }
        return MaxArea;
    }
};

整体思路

利用双层for循环,遍历所有情况,并且在第一层for循环中加入判断条件用于剪枝。找到所有情况中最优的哪一个

版本二: 双指针方法(官方解法)

class Solution {
    
    
public:
    int maxArea(vector<int>& height) {
    
    
        unsigned lp = 0, rp = height.size() - 1, maxArea = 0;
        while (lp < rp)
        {
    
    
            maxArea = std::max(maxArea, std::min(height.at(lp), height.at(rp)) * (rp - lp));
            height.at(lp) > height.at(rp) ? --rp : ++lp;
        }
        return maxArea;
    }
};

整体思路

一开始先设定两个指针,一个指向数组的开头,一个指向数组的结尾。初始化当前最大面积为0.

根据当前两个指针的位置计算得出一个新面积,设置当前最大面积为:
当前最大面积 = max(当前最大面积,新面积)

接着移动两个指针中取得高度较小的哪一个指针:

  • 如果左边比右边高,将右指针往左移一位
  • 如果左边比右边低,将左指针往右移一位

再次计算新的面积,改变当前最大面积的值,然后再次移动,直到两个指针相遇方能结束。

学到了什么

1、第一次接触到双指针方法
2、熟悉了三元表达式的写法:boolexp?exp1:exp2;

结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/youyadefeng1/article/details/113406139