Leetcode:Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.app

分析:這道題與Trapping Rain Water、Largest Rectangle in Histogram有共通之處。解決這三道題,咱們都要保持對數字的敏感性,發現隱含在數字後的性質。對於這道題,container裝水的量是有短板決定的。可能你們都知道這點,但如何利用這點來完成一個O(n)的算法則值得思考。Brute-force的算法複雜度爲O(n^2),但其實在brute-force算法中的不少計算是沒必要要的,咱們大可在計算的過程當中將這些沒必要要(不多是最優解)的狀況prune掉。對於一個高度的line,咱們只需求以該line爲短板的最大裝水量便可,知足最大裝水量的container是由該line和離該line最遠的且比該line高的line組成。在代碼中咱們能夠用two pointers來實現上述思想。一旦一個line是以短板的角色出現後,咱們即可以將其剔除,在後續計算中不考慮以它爲邊界的container。代碼以下:spa

class Solution {
public:
    int maxArea(vector<int> &height) {
        int result = 0;
        int left = 0, right = height.size()-1;
        
        while(left < right){
            result = max(result, (right-left)*min(height[left], height[right]));
            if(height[left] < height[right])
                left++;
            else right--;
        }
        
        return result;
    }
};
相關文章
相關標籤/搜索