前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T32-盛最多水的容器

【leetcode刷题】T32-盛最多水的容器

作者头像
木又AI帮
修改2019-07-18 09:58:12
2990
修改2019-07-18 09:58:12
举报
文章被收录于专栏:木又AI帮木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

代码语言:javascript
复制
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

【中文题目】

给定 n 个正整数 a1,a2,…,an,其中每个点的坐标用(i, ai)表示。 画 n 条直线,使得线 i 的两个端点处于(i,ai)和(i,0)处。请找出其中的两条直线,使得他们与 X 轴形成的容器能够装最多的水。

注意:你不能倾斜容器,n 至少是2。

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

示例:

代码语言:javascript
复制
输入: [1,8,6,2,5,4,8,3,7]
输出: 49

【思路】

本题和【T31-接雨水】类似,需要两个指针l和r,当height[l] < height[r]时,l->r区间的面积肯定大于l->r-1区间的面积(和l->r区间相比,l->r-1区间矩形的高<=height[l],而长减1),因此l->r的所有以l开始的子区间都不用遍历;同理height[l] >= height[r]时,l->r区间的面积肯定大于l+1->r区间的面积,因此l->r的所有以r结束的子区间都不用遍历。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l, r = , len(height) - 
        res = 
        while l < r:
            if height[l] < height[r]:
                res = max(res, height[l] * (r - l))
                l += 
            else:
                res = max(res, height[r] * (r - l))
                r -= 
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    int maxArea(vector<int>& height) {
        int l=, r=height.size()-1;
        int res = ;
        while(l < r){
            if(height[l] < height[r]){
                res = max(res, height[l] * (r - l));
                l++;
            }else{
                res = max(res, height[r] * (r - l));
                r--;
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档