LeetCode11题——container with most water

问题描述
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 and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49
解法思路
枚举法,直接将所有可能情况计算出来

C++代码

class Solution {
public:
    int maxArea(vector<int>& height) {
        int n=height.size();
        int max=0;
        for(int i=0;i<n;++i)//遍历所有可能的容器面积
        {
            for(int j=0;j<i;++j)
            {
                int h=(height[i]>height[j])?height[j]:height[i];
                int volume=h*(i-j);
                if(volume>max) max=volume;
            }
        }
        return max;
    }
};

结果分析
Runtime: 1232 ms, faster than 25.87% of C++ online submissions for Container With Most Water.
Memory Usage: 9.9 MB, less than 94.99% of C++ online submissions for Container With Most Water.

可以看出,算法时间效率特别差,需要改进

改进思路
从容器的宽度出发,第一条和最后一条容器是最宽的,向中间搜索,如果高度还没有两端的高,就抛弃,剩余部分,比较容器的大小,这样可以大大提高效率。

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

最终结果:Runtime: 20 ms, faster than 98.54% of C++ online submissions for Container With Most Water.
Memory Usage: 10.2 MB, less than 5.15% of C++ online submissions for Container With Most Water.

你可能感兴趣的:(LeetCode刷题记录)