LeetCode (11)-- Container With Most Water

来源:互联网 发布:浙江软件行业协会 编辑:程序博客网 时间:2024/06/07 05:13

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.

这道题的要求是给定整形数组a,(i, ai)表示坐标点,这些坐标点向x轴作垂直的线。找到两条线,使其和x轴共同构成的容器,可以装下最多的水。(注意,不允许倾斜容器)
面积为两个线中较短者为高,以及两线的距离为长相乘得到。

一开始是使用两层循环,但是会超时。因此考虑从vector两头开始,向中间移动,直到两个重合。这样做可以省去计算不必要的面积。规则是:当左侧的线短时,左线右移;当右侧的线短时,右线左移。在此做一个解释:当左侧的线短时,如果左移右侧线,计算得的面积只会比当前面积更小,因为长度首先在减少,而且高度也只会小于等于左侧的线,因此可以省略计算当前左侧线和其余所有线所围成的面积,所以右移左侧线;当右侧线短时,同理可得到要左移右侧的线。
代码如下:

 int maxArea(vector<int>& height) {        int max = 0;        int s = 0;        int l = 0;        int r = height.size()-1;        while (r > l){            if (height[l] <= height[r])            {                s = height[l] * (r - l);                if (s > max)max = s;                l++;            }            else            {                s = height[r] * (r - l);                if (s > max)max = s;                r--;            }        }        return max;    }
原创粉丝点击