1. 程式人生 > >【leetcode】11. Container With Most Water最大水容器(中等難度)

【leetcode】11. 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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解法一:
對所有的數進行不重複的的組隊遍歷,並寫出一個函式,把每對數放進去計算出大小儲存,直至所有的數遍歷完成,則找到了最大值。

 //窮舉法,效能比較差。
    public static int maxArea(int[] height) {
        int sum = 0;
        if (height.length == 1 || height.length ==0) return 0;
        for (int i=0;i<height.length;i++){ //利用窮舉法,計算海水的面積,計算出最大的值並儲存下來。
            for (int j=i+1;j<height.length;j++){
                sum = Math.max(sum,calateSum(height,i,j));
            }
        }
        return sum;
    }
    //計算兩個數字之間的海水大小
    public static int calateSum(int[] height,int a,int b){
        return Math.min(height[a],height[b])*Math.abs(a-b);
    }

解法二:
為了減少時間複雜度,則想到了設定兩個指標,類似於快速排序,頭指標和尾指標,計算兩個指標之間的海水容納量,並指標往對應陣列值比較小的地方移動,兩個指標逐漸匯合,直至相鄰,計算結束。

 public static int maxArea1(int[] height){
        int maxArea=0;int l = 0; int r = height.length - 1;//定義左邊界和右邊界
        while (l<r){
            maxArea =  Math.max(maxArea, Math.min(height[l],height[r])*(r-l));
            if (height[l]<height[r]){
                l++;
            }else {
                r--;
            }
        }
        return maxArea;
    }