LeetCode C++ 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

題意:給出座標系上各豎線的高度數組,令兩條豎線和X軸形成一個二維容器,求出能夠裝的最多的水,或者說這兩條豎線(的短板)和容器形成的最大面積。

思路:最大化介於兩條豎線之間的矩形面積。計算面積時使用的是兩條豎線中更短的那條線。

最開始,我們可以用最左邊和最右邊的兩條線,得到最大的寬度。但是這不一定是最大的面積,因爲可能存在更高的豎線。

所以,我們每次都從更短的一邊向中間搜索

  • 如果遇到更長的豎線,比較並可能更新最大面積;此時,如果短線變了,則換到另一邊重複做同樣的事情。
  • 如果遇到的是更短的豎線,則短邊沒有變化,繼續向中間搜索。

代碼:

class Solution {
public:
    int maxArea(vector<int>& height) { 
        int w = height.size() - 1, lo = 0, hi = w, maxV = w * min(height[lo], height[hi]);
        while (lo < hi) {
            while (lo < hi && height[lo] <= height[hi]) { //左邊是短板
                --w;
                if (height[lo + 1] > height[lo]) 
                    maxV = max(maxV, w * min(height[lo + 1], height[hi]));
                ++lo;
            } 
            while (lo < hi && height[lo] > height[hi]) { //右邊是短板
                --w; 
                if (height[hi - 1] > height[hi])
                    maxV = max(maxV, w * min(height[lo], height[hi - 1]));
                --hi;
            }   
        }
        return maxV;
    }
};

效率:

執行用時:16 ms, 在所有 C++ 提交中擊敗了79.39% 的用戶
內存消耗:7.4 MB, 在所有 C++ 提交中擊敗了100.00% 的用戶
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章