LeetCode解题报告--Container With Most Water

题目:最大的盛水容器

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.

原题链接地址:https://leetcode.com/problems/container-with-most-water/
分析:题意是给定长度为n整型数组height;分别构成(1,height[1]),(2,height[2]),….(n,height[n])坐标点,找出两个点分别过这些点做垂直X轴的垂线,以及连接这两个点,与X轴构成长方形容器,求该容器的最大值!
通过两个变量leftHeiht,rightHeight分别指向数组height的最左端和最右端,这样宽度最大,当缩小宽度,则需要寻找较大的高度。
做简单证明
这里写图片描述
Java 代码:(accepted)

public class ContainerWithMostWater {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = { 1, 4, 5, 6, 3, 8, 9, 12, 45 };
        System.out.println("Max Area is : " + maxArea(a));
        int[] a1 = { 12,45,32,78,11,23,14 };
        System.out.println("Max Area is : " + maxArea(a1));
        int[] a2 = { 90,34,45,21,43,32};
        System.out.println("Max Area is : " + maxArea(a2));
    }

    public static int maxArea(int[] height) {

        int maxArea = 0; // The max area
        int leftHight = 0;
        int rigtHight = height.length - 1;

        while (leftHight < rigtHight) {
            //Calculate the max area 
            maxArea = Math.max(maxArea, (rigtHight - leftHight)
                    * Math.min(height[leftHight], height[rigtHight]));
            //Because of cast effect, hence choose shortest height

            if (height[leftHight] > height[rigtHight])
                rigtHight--;
            else
                leftHight++;
            //System.out.println("Left: " + height[leftHight] + " " + leftHight + " Right: " + height[rigtHight] + " " + rigtHight);
            //System.out.println("Max Area: " + maxArea);
        }
        return maxArea;
    }

}

测试结果:

Max Area is : 30
Max Area is : 92
Max Area is : 172

相关代码放在个人github:https://github.com/gannyee/LeetCode/tree/master/src

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值