1. 程式人生 > >最大容積 Container With Most Water

最大容積 Container With Most Water

pre 技術 math 枚舉 算法 面積 時間 圖片 設置

2018-07-31 17:28:42

問題描述:

技術分享圖片

技術分享圖片

問題求解:

很容易想到的是Brute Force,也就是枚舉所有可能的pairs,這種解法的時間復雜度為O(n ^ 2),由於本題的數據規模較大,會TLE。那麽就要對算法進行改進了。

這裏用到的解法是Two Pointers,左右各設置一個指針,l 和 r。

首先計算最初的面積 curArea = Math.min(height[l], height[r]) * (r - l)。

如果height[l] < height[r],那麽可以想見的是將右邊線無論如何向左調整,都是無法繼續增大面積的,因此此時只能調整左邊線,l++。

同理height[l] > height[r],那麽只能調整右邊線來謀求更好的解,r--。

如果出現了height[l] = height[r],則可任意調整左邊或者右邊來謀求更好的解。

    public int maxArea(int[] height) {
        int res = 0;
        int l = 0;
        int r = height.length - 1;
        while (l < r) {
            int curArea = Math.min(height[l], height[r]) * (r - l);
            if (curArea > res) res = curArea;
            if (height[l] < height[r]) l++;
            else r--;
        }
        return res;
    }

最大容積 Container With Most Water