1. 程式人生 > >Leetcode 11. Container With Most Water

Leetcode 11. Container With Most Water

如何盛最大的水? 陣列代表高度, 盛的水量V= min( height[left] 、 height[right] ) * 底部的長度= [right- left] 雙指標解決這個問題, 從左邊、右邊不斷逼近, 逐漸取得最大值,

如何進行更新, 不斷進行更新逼近,因為決定的是height[left]、height[right],中的最小值, 所以當,對right 和height 採用快速排序中不斷畢竟的原則

答案是有,用兩個指標從兩端開始向中間靠攏,如果左端線段短於右端,那麼左端右移,反之右端左移,知道左右兩端移到中間重合,記錄這個過程中每一次組成木桶的容積,返回其中最大的。

英文解釋該中情況

Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don’t support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left. 快速排序

class Solution {
    public int maxArea(int[] heights) {
       int result=0;
        int n = heights.length;
        int left=0, right =n-1;
        while(left<right){
            int tmp= (right-left) * Math.min(heights[left],heights[right]);
            result = Math.max(tmp,result);
            if
(heights[left]<heights[right]) { ++left; } else { --right; } } return result; } }

如何進行改進

int maxArea(vector<int>& height) {
    int water = 0;
    int i = 0, j = height.size() - 1;
    while (i < j) {
        int h = min(height[i], height[j]);
        water = max(water, (j - i) * h);
        //i<j 必須滿足該中情況, 類似快速排序
        while (height[i] <= h && i < j) i++;
        
        while (height[j] <= h && i < j) j--;
    }
    return water;
}