【LeetCode】11. Container With Most Water 解题小结

 题目:

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.

一般的方法就是嵌套两个for循环,不过提交的时候就超时了。那么换个角度考虑,先从最宽的情况,也就是height.size()-1到0这个横坐标之间最大的水容量,比较两者的an-1和a0哪个小一些。然后逐渐往中间靠拢,只有比min(an-1,a0)高的才会被考虑,计算水容量大小,如果比之前大,则更新axis。

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

转载于:https://www.cnblogs.com/Doctengineer/p/5813127.html

你可能感兴趣的:(【LeetCode】11. Container With Most Water 解题小结)