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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章