[LeetCode]--Container With Most Water

来源:互联网 发布:网络剧投资 编辑:程序博客网 时间:2024/06/16 09:12

题目

       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 and n is at least 2.

      中文题意:由非负整数 a1a2, ..., an, 分别代表坐标 (iai),n条垂直于x轴的线段i及由(iai)和 (i, 0)作为端点组成。请找到两条线段,与x轴组成一个容器,使得这个容器盛水最多。

      注意:容器不能倾斜且只能找两条线段。

分析

         首先我们看一下如何判断桶能装多少水,设找到两条边aiaj,ai < aj,则显然水不能超过容器的最短板,那么此容器的最大容积为(|i - j|)*ai。也即对于所有的容器,容积为两条线段间的距离乘以较短线段的长度。
       明确了容积的求法,这道题最直观的想法就是利用嵌套循环,将所有线段两两组合成容器,并取容积的最大值,得到所需结果。但是事实证明,嵌套循环不能满足题目通过时间的限制,时间复杂度不满足需求,我们需要考虑一种时间复杂度小于O(n^2)的算法。
       由于容器的容积取决于被选择的线段中较短的一个,我们可以利用这个特点,对线段进行简化筛选。假定a1a2, ..., an,是一个数组,那么从数组的两端开始检验,假设两边aiaj,ai < aj 且 i < j,求其容积后,因为ai < aj,那么较长边aj对于此桶的容积没有影响,因此将下标 i 下移一个位置;若aiaj,ai > aj 且 i < j,则将下标 j  上移一个位置并继续计算桶的容积,直到 i=j 为止。这样算法就用扫描n次所有线段变成了扫描1次所有线段,大大降低了复杂度。

解答

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

      时间复杂度为O(n^2)。

原创粉丝点击