最多裝水---雙向指針往中間移動

1,leetCode題目地址

https://leetcode-cn.com/problems/container-with-most-water/

2,題目

給你 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。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/container-with-most-water
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

3源碼:

class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;
        for(int i= 0,j=height.length-1;i<j;){
            //水桶能成多少水,取決於較短的那個木棒。
            //i++或者j-- 表示左右邊界移動。
            int minHeight = height[i]< height[j]?height[i++]:height[j--];
            maxArea = Math.max(maxArea,(j-i+1)* minHeight);
        }

        return maxArea;
    }
}

 

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