小白筆記-------------------------------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.


普通思路就是兩個for循環全部遍歷,但是會超時,這裏需要考慮的就是剪枝的問題,那麼如何減枝?

很容易想到的方法就是類似與左右子樹的減枝,就是用兩個遊標,左右遊標來控制,

那麼定義了左右遊標之後,如何保證最大的值仍能被遍歷到呢?

首先,將值與最大值比較,保存

接着,因爲減大值的話沒有減枝的作用,所以選擇小的一端往裏進一格,至此問題就解決了。

class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;//初始化一個最大值
        int Area = 0;
        int minHeight = 0;
        int n = height.length;
        int left = 0;
        int right = n-1;
        while(left < right){
            minHeight = height[left] <= height[right]?height[left]:height[right];
            Area = (right-left) * minHeight;
            if(Area > maxArea){
                maxArea = Area;
            }
            if(height[left] < height[right]){
                left++;
            }else{
                right--;
            }
            
        }
                
        
        return maxArea;
    }
}


發佈了102 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章