码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode解题报告--Container With Most Water

时间:2015-08-13 18:00:02      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   算法   code   面经   

题目:最大的盛水容器

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

标签:leetcode   java   算法   code   面经   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!