[Leetcode] 107. 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.

解題之法

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0, i = 0, j = height.size() - 1;
        while (i < j) {
            res = max(res, min(height[i], height[j]) * (j - i));
            height[i] < height[j] ? ++i : --j;
        }
        return res;
    }
};

分析

這道求裝最多水的容器的題和那道 Trapping Rain Water 收集雨水 很類似,但又有些不同,那道題讓求整個能收集雨水的量,這道只是讓求最大的一個的裝水量,而且還有一點不同的是,那道題容器邊緣不能算在里面,而這道題卻可以算,相比較來說還是這道題容易一些,我們需要定義i和j兩個指針分別指向數組的左右兩端,然后兩個指針向中間搜索,每移動一次算一個值和結果比較取較大的,容器裝水量的算法是找出左右兩個邊緣中較小的那個乘以兩邊緣的距離。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容