11. Container With Most Water

题目

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

翻译

给定n个非负整数12,...,n,其中每个表示坐标(ii处的点绘制n条垂直线,使得线i的两个端点在(ii)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,使得容器含有最多的水。

注意:您不能倾斜容器,n至少为2。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int right=height.size()-1;
        int area=0,maxarea=0,left=0;
        while(left<right){
            if(height[left]<height[right]){
              area=height[left]*(right-left);
              left++;
            } 
            else {
                area=height[right]*(right-left);
                right--;
                
            }
            maxarea=max(maxarea,area);
        }
        return maxarea;
    }
};

分析

做了一段时间leetcode,现在看见vector就想排序,不过这题不能排序

本题可以用一个maxarea储存每一次的水容量,并在这次的循环中通过MAX函数与上一次的容量相比较

而水容量等两条线段中较短的乘以两条线的距离   

循环的关键条件在于,每一次循环变动的边应该是较短的那条



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值