数组-装最多水的容器-中等

描述
给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai)。画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)和(i, 0)。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。
容器不可倾斜。
您在真实的面试中是否遇到过这个题?  是
样例

给出[1,3,2], 最大的储水面积是2.


题目链接

分析

        对于这道题目,需要紧扣的几个字眼“找到两条线”。所以我们可以从头尾两端去搜寻能装最多水的面积。对于面积的计算,我们去两端最小的那个高度,长度为两端的位置之差。最后返回最大的那个面积。

程序

class Solution {
public:
    /**
     * @param heights: a vector of integers
     * @return: an integer
     */
    int maxArea(vector<int> &heights) {
        // write your code here
        if(heights.empty())
            return 0;
        int start = 0;
        int end = heights.size() - 1;
        int max = 0;
        int cur;
        while(start < end){
            if(heights[start] > heights[end]){
                cur = heights[end] * (end - start);
                end--;
            }
            else{
                cur = heights[start] * (end - start);
                start++;
            }
            if(cur > max)
                max = cur;
        }
        return max;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80736962