11. Container With Most Water Medium

来源:互联网 发布:怎样加入淘宝外卖 编辑:程序博客网 时间:2024/06/14 00:00

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.

思路: 1.双层循环逐个算出每个容器的装水量,比较选出最大的一个。复杂度为O(n ^2),超时。

 2.先算出最外层的容器装水量,若不是最大的,那么最大的容器必定没它宽,而最大的容器高度一定比最外层的高,所以我们每次只需将短边向内移动,比较出最大的容器,复杂度为O(n)。

注意:短板效应。

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


0 0