11. 盛最多水的容器 Container With Most Water

给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (iai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (iai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49

①线性复杂度

static const auto x = [](){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    return NULL;
}();
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();//数组长度
        
        int i = 0, j = n-1;//从左和从右
        int ans = area(height,i,j);//记录答案
        for(int k = 1; k < n; ++k)
        {
            
            if(height[i] < height[j])//左高度小于右高度就增加i
            {
                i++;
            }
            else//左高度大于右高度就减小j
                j--;
            ans = max(ans,area(height,i,j));
        }
        return ans;
    }
    
    int area(vector<int>& height, int i, int j)
    {
        return abs(j-i) * min(height[i],height[j]);
    }
};

②暴力。。。

static const auto x = [](){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    return NULL;
}();
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        int max = 0;
        
        for(int i = 0; i < n; i++)
        {
            int tempMax = 0;
            for(int j = 0; j < n; j++)
            {
                int temp = abs(i - j) * min(height[i], height[j]);
                if(tempMax < temp)
                    tempMax = temp;
            }
            if(max < tempMax)
                max = tempMax;
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33655674/article/details/81449143
今日推荐