天天看點

LeetCode 11. 盛最多水的容器(JAVA)

題目

給你 n 個非負整數 a1,a2,...,an,每個數代表坐标中的一個點 (i, ai) 。在坐标内畫 n 條垂直線,垂直線 i 的兩個端點分别為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

說明:你不能傾斜容器,且 n 的值至少為 2。

圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為49。

示例:

輸入:[1,8,6,2,5,4,8,3,7]
輸出:49           

解題思路

public int maxArea(int[] height) {
        //雙指針,檢測到面積比存量的大,就儲存最大的,然後低的索引向内部移動
        int left = 0;
        int right = height.length-1;
        int maxArea = 0;
        while (left < right){
            int width = right - left;
            int curArea =  Math.min(height[left], height[right]) * width;
            maxArea = Math.max(maxArea, curArea);
            if (height[left] <= height[right]){
                left++;
            }
            else {
                right--;
            }
        }
        return maxArea;
    }