LeetCode 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.
Subscribe to see which companies asked this question.

題目

給定 n 個(gè)非負(fù)整數(shù) a1, a2, ..., an, 每個(gè)數(shù)代表了坐標(biāo)中的一個(gè)點(diǎn) (i, ai)。畫 n 條垂直線,使得 i 垂直線的兩個(gè)端點(diǎn)分別為(i, ai)和(i, 0)。找到兩條線,使得其與 x 軸共同構(gòu)成一個(gè)容器,以容納最多水。
注意事項(xiàng)
容器不可傾斜。
樣例
給出[1,3,2], 最大的儲(chǔ)水面積是2

分析

用兩根指針一頭一尾,分別計(jì)算面積,然后選取高度小的那邊向中間移動(dòng),因?yàn)檫@樣才可能存在更大的面積,更新最大的面積,最后就是結(jié)果。

Paste_Image.png

代碼

public class Solution {
    /**
     * @param heights: an array of integers
     * @return: an integer
     */
    int computeArea(int left, int right,  int[] heights) {
        return (right-left)*Math.min(heights[left], heights[right]);
    }
    
    public int maxArea(int[] heights) {
        //兩根指針,一頭一尾計(jì)算,短的那根指針向中間移動(dòng),因?yàn)橹挥羞@種情況才存在更大的情況
        int left = 0, right = heights.length-1;
        int res = 0;
        
        while(left < right) {
            res = Math.max(res, computeArea(left,right,heights));
            if(heights[left] < heights[right]) {
                left++;
                //如果小于則不必要計(jì)算,直接跳過(guò)
                while(heights[left] <= heights[left-1] && left<right)
                    left++;
            }
            else {
                right--;
                while(heights[right] <= heights[right+1] && left <right)
                    right--;
            }
        }
        return res; 
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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