[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兩個指針分別指向數(shù)組的左右兩端,然后兩個指針向中間搜索,每移動一次算一個值和結(jié)果比較取較大的,容器裝水量的算法是找出左右兩個邊緣中較小的那個乘以兩邊緣的距離。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容