11. Container With Most Water

FreeeLinux發表於2017-03-22
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.

這道題就是一個在第一象線有多個豎線,豎線長度就是高。兩條豎線之間距離就是底。求最大面積。不過由於水桶原理,最大面積是由最短的豎線決定的。同時,我們還要考慮底。因為S=底*高。

方法是從兩邊開始查詢,我們儘量要找兩條豎線都很高,並且豎線之間距離很遠的組合。所以對於中間低的豎線並且近的豎線可以不計算。每次計算完,更新max就可以了。

我寫的原始版本:

class Solution {
public:
    int maxArea(vector<int>& height) {
        const int size = height.size();
        if(size < 2)
            return 0;
        int l = 0, r = size - 1;
        int res = 0;
        for(int i=0, j=size-1; i<j; ) {
            if(height[i] > height[l])
                l = i;
            if(height[j] > height[r])
                r = j;
            res = std::max(res, std::min(height[i], height[j]) * (r-l));
            if(height[i] < height[j])
                ++i;
            else
                --j;
        }
        return res;
    }
};

精簡版本:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0, j = height.size() - 1;
        int res = 0;
        while(i < j) {
            int h = std::min(height[i], height[j]);
            res = std::max(res, h * (j - i));
            while(height[i] <= h && i < j) ++i;
            while(height[j] <= h && i < j) --j;
        }
        return res;
    }
};

相關文章