首页 > 其他 > 详细

LeetCode解题报告--Container With Most Water

时间:2015-08-13 17:58:03      阅读:289      评论:0      收藏:0      [点我收藏+]

题目:最大的盛水容器

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/
分析:该题难度不大,题意是给定一个int型数字num,判断其是否为回文数字。主要有两种情况:
1. num >= 0, 当num = 00000, 含多个零时,要单独讨论;
2. num < 0, 先转为正数, 再进行判断。

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode解题报告--Container With Most Water

原文:http://blog.csdn.net/github_27609763/article/details/47616077

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!