美文网首页LeetCode
LeetCode-array-Container With Mo

LeetCode-array-Container With Mo

作者: 萤火之森ss | 来源:发表于2017-07-03 18:30 被阅读67次

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

意思是,有一个非负数的数组,数组中每个元素就是一条垂直的线,这条线的两端坐标是(i,ai),( i,0),i是数组元素的下标,
选取两条组成面积最大的,计算出值,注意,矩形不能倾斜,,,


1499077569(1).jpg

如上图。
从java代码解决,直接上代码

/**
 * Created by Wangjianxin on 2017/7/3 0003.
 */
public class ContainerWithMostWater {

    public int maxArea(int[] height) {
        int oldmax = 0;  
        int newmax = 0;
        int len = height.length;

        int left = 0;
        int right = len - 1;

        while (left < right){ 
            //计算面积,看上图可以知道,需要两条线中短线的高,和两线之间的距离宽
            if(height[left] > height[right]){ 
                oldmax = height[right] * (right - left);
            }else {
                oldmax = height[left] * (right - left);
            }

            if(newmax < oldmax){
                newmax = oldmax; //得到最大值
            }
            //这里用于从两头往中间一直计算,只要两条线中壹条短一些, 就应该在那条短的线继续向前或者向后的其他线在计算
            if(height[left] > height[right]){
                right --;
            }else {
                left ++;
            }

        }
        return newmax;
    }
}

相关文章

  • LeetCode-array-Container With Mo

    首先看题目:Given n non-negative integers a1, a2, ..., an, wher...

  • 2018-03-20

    mo mo

  • mo'mo

    哦哦生日礼物

  • Mo SSL, Mo Problems

    Mo SSL, Mo Problems mac重装后,更新到10.11.安装python3的时候,发现一直在报错,...

  • mo

    我耳边的聒噪 是别人的兴趣 我习以为常的沉默 是他们眼中的不合群 为了生活 必须打起精神 去迎合每个人 偶尔放松下...

  • mo

    走出大楼 撑起伞 走过一地黄色的花瓣 和一群疲惫的人 你知道生活不易 我知道 我面无表情

  • A Mo

    A Mo By Cheng Lie It's bucketing down, it's the very show...

  • MO~

    摸(摸索) 摸索着,牙牙学语理解大人们的言语; 摸索着,蹒跚学步奔向大人们的世界; 摸索着,摸索着长大。 磨(磨练...

  • “mo”

    有的字,一个就可以拨动心弦;有个人,一想起来就泪流满面。2017年读李立欣老师的《进门唤一声“mo”方知在世...

  • 3Cr2Mo!3Cr2Mo!3Cr2Mo磨具钢

    3Cr2Mo!3Cr2Mo!3Cr2Mo磨具钢 一、3Cr2Mo磨具钢的简介: 3Cr2Mo在中国广泛应用,出厂硬...

网友评论

    本文标题:LeetCode-array-Container With Mo

    本文链接:https://www.haomeiwen.com/subject/whszcxtx.html