11. 盛最多水的容器

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
容器服务 Serverless 版 ACK Serverless,952元额度 多规格
容器服务 Serverless 版 ACK Serverless,317元额度 多规格
简介: 11. 盛最多水的容器

11. Container With Most Water


1.小白解法

class Solution
{
public:
    int maxArea(vector<int> &height)
    {
        auto left = height.begin();
        auto right = height.end() - 1;
        int sum = 0;
        while (left != right)
        {
            if (*left <= *right)
            {
                int tmpsum = *left * (right - left);
                if (tmpsum > sum)
                {
                    sum = tmpsum;
                }
                left++;
            }
            if (*left > *right)
            {
                int tmpsum = *right * (right - left);
                if (tmpsum > sum)
                {
                    sum = tmpsum;
                }
                right--;
            }
        }
        return sum;
    }
};


很暴力的解法,将所有结果算出,找到最大的结果。


简化版本

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


网上解法把我最初的想法简化了一下。


感悟

自己通关

目录
相关文章
|
5月前
|
存储 容器
LeetCode刷题---11. 盛最多水的容器(双指针-对撞指针)
LeetCode刷题---11. 盛最多水的容器(双指针-对撞指针)
|
12月前
|
算法 容器
【算法专题突破】双指针 - 盛最多水的容器(4)
【算法专题突破】双指针 - 盛最多水的容器(4)
34 0
|
算法 测试技术 容器
【算法挨揍日记】day02——双指针算法_快乐数、盛最多水的容器
题目: 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为:
55 0
|
4月前
|
算法 测试技术 程序员
力扣经典150题解析之二十八:盛最多水的容器
力扣经典150题解析之二十八:盛最多水的容器
31 0
|
5月前
|
容器
11. 盛最多水的容器
11. 盛最多水的容器
32 1
|
4月前
|
容器
11.盛最多水的容器
11.盛最多水的容器
|
4月前
|
算法 容器
【经典LeetCode算法题目专栏分类】【第1期】左右双指针系列:盛最多水的容器、接雨水、回文子串、三数之和
【经典LeetCode算法题目专栏分类】【第1期】左右双指针系列:盛最多水的容器、接雨水、回文子串、三数之和
|
5月前
|
容器
leetcode代码记录(盛最多水的容器
leetcode代码记录(盛最多水的容器
24 1
|
5月前
|
算法 容器
【优选算法】—Leetcode—11—— 盛最多水的容器
【优选算法】—Leetcode—11—— 盛最多水的容器
|
5月前
|
容器
【力扣】11. 盛最多水的容器
【力扣】11. 盛最多水的容器