前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Container With Most Water

Leetcode: Container With Most Water

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:15:57
4010
发布2019-01-22 15:15:57
举报

题目: 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.

思路分析: 给定数组A[],求直线((i, 0), (i, A[i]))、((j, 0), (j, A[j]))和X轴围成的体积重最多能装多少水。这个装水的多少是由abs(i - j)和min(A[i], A[j])共同决定的。两者的积越大,则能装的水越多。 所以我们先让abs(i - j)取最大值,通过左右两个指针,逐渐移动,逐步调整min(A[i], A[j])和abs(i - j)得到最大值。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    int maxArea(vector<int>& height)
    {
        int count = int(height.size());
        if (count == 0) return 0;
        int left = 0;
        int right = count - 1;
        int maxArea = 0;//最大面积
        int curArea = 0;//当前面积
        while (right > left)
        {
            curArea = min(height[left], height[right]) * (right - left);
            if (curArea > maxArea) maxArea = curArea;
            if (height[left] > height[right]) --right;
            else ++left;
        }
        return maxArea;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年04月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档