1. 程式人生 > >LeetCode——盛最多水的容器(Java)

LeetCode——盛最多水的容器(Java)

給定 n 個非負整數 a1a2,...,an,每個數代表座標中的一個點 (iai) 。畫 n 條垂直線,使得垂直線 i 的兩個端點分別為 (iai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

注意:你不能傾斜容器,n 至少是2。

[1,3,2]->2

class Solution {//高度取決於最短邊,從兩邊移動指標降低複雜度
    public static int min(int a,int b)
    {
        if(a<b)
            return a;
        else
            return b;
    }
    public static int max(int a,int b)
    {
        if(a>b)
            return a;
        else
            return b;
    }
    public int maxArea(int[] heights) {
        int i = 0;  
        int j = heights.length - 1;  
            
        int result = 0;  
        while(i < j)  
        {  
            int area = (j - i) * min(heights[i], heights[j]);  
            result = max(result, area);  
               
            if (heights[i] <= heights[j])  
            {  
                i++;              
            }  
            else  
            {  
                 j--;  
            }  
         }  
           
         return result;  
    }
}