leetcode—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(int[] height) {
        if(height==null || height.length<=0) return 0;
        int index1 = 0;
        int index2 = height.length-1;
        int max = 0;
        while(index1<index2){
            max = Math.max(max,Math.min(height[index1],height[index2])*(index2-index1));
            if(height[index1]<height[index2]){
                index1++;
            }else{
                index2--;
            }
        }
        return max;
    }
}

和Two sum類似,利用夾逼準則,起始條件是一個索引在數組最左邊,另外一個索引在數組最右邊,從兩邊向中間靠攏,前進的準則是兩個索引對應的數組值,如果左邊的比較小,那麼左邊的像右滑動,如果右邊的比較小,右邊的像左滑動,因爲這個裝水是利用的短板原理,如果左邊的比較小,滑動他,有可能會變大,但是滑動右邊的,一定會變小,因爲不是橫座標變小了就是縱座標變小

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章