LeetCode 11 - Container With Most Water

荒凉一梦 提交于 2020-01-25 10:29:21

一、问题描述

Description:

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.

给定 n 个非负整数 a1,a2,...,an,构造 n 条垂直于x-轴的直线,每条直线都是从起点 (i,0) 到终点 (i,ai)。 任选两条直线,都可以与x-轴一起构成一个容器,求这些容器中能装的最大的水量。

假定容器不可以倾斜。


二、解题报告

1. 解法一:O(n2)

直接遍历,枚举容器的两个边界,记录最大值:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxA = 0;
        for(int i=1; i<height.size(); ++i)
        {
            for(int j=i+1; j<height.size(); ++j)
            {
                if(height[i] < height[j])
                    maxA = height[i]*(j-i);
                else
                    maxA = height[j]*(j-i);
            }
        }
        return maxA;
    }
};

时间复杂度是O(n2),大数据超时!


2. 解法二:O(nlog2n)

这种方法,我们用一个vector<pair<int, int>>来存储<高度, 下标>,然后将 vector 按高度大小排序。排序之后,对于vector[i]来说,vector[i+1,i+2,...,n-1]的高度都比它大。

故以vector[i]为较短边的容器中,要使水量最大,只需要距离最远,即分别计算vector[i+1,i+2,...]内按原始位置排列最左边和最右边的直线,取两者的较大值。

bool cmp(pair<int,int> &p1, pair<int,int>&p2)
{
    return p1.first < p2.first;
}

class Solution {
public:
    int maxArea(vector<int>& height) {
        vector<pair<int, int>> v;    // 表示<高度,下标>
        int n = height.size();
        for(int i=0; i<n; ++i)
            v.push_back(make_pair(height[i], i+1));

        sort(v.begin(),v.end(),cmp); // 排序

        int left = v[n-1].second;    // 记录最左边和最右边的位置
        int right = left;
        int res = 0;
        for(int i=n-2; i>=0; --i)
        {
            res = max(res, max(v[i].first*(v[i].second-left), 
                            v[i].first*(right-v[i].second)));
            left = min(left, v[i].second);  // 更新
            right = max(right, v[i].second);
        }
        return res;
    }
};

由于STL sort()是基于快排,时间复杂度是O(nlog2n),故本算法总的时间复杂度是O(n) + O(nlog2n) + O(n) = O(nlog2n).

AC 时间 68ms!


3. 解法三:O(n)

思路:两个指针 i, j 分别从前后向中间移动,两个指针分别表示容器的左右边界。每次迭代,先更新最大容量,然后把高度小的边界对应的指针往中间移动一位。

正确性:由于水的容量是由较小的那个边界决定的。在某次迭代中,假设 height[i] < height[j],那么 j 左移一位肯定不会使水的容量增大:

  • 若 j 左移一位后,height[j] 仍然大于 height[i],由于距离缩短了,水的容量反而减少了。
  • 若 j 左移一位后,height[j] 小于 height[i],由于距离缩短了,同时高度也减少了,水的容量也减少了。

所以,只有 i 增加才有可能使水的容量增大。

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

AC 时间 20ms!





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!