【LeetCode从零单刷】Container With Most Water

来源:互联网 发布:属下知罪by枯目结局 编辑:程序博客网 时间:2024/06/04 18:45

题目:

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.

解答:

暴力求解,不用说,超时不能AC:

class Solution {public:    int area(int i, int j, int ai, int aj)    {        int length = (i - j > 0) ? (i - j) : (j - i);        int width  = (ai > aj) ? aj : ai;        return (length * width);    }        int maxArea(vector<int>& height) {        int size = height.size();        int ans = -1;        for(int i=1; i <= size; i++)        {            for(int j=1; j <= size; j++)            {                int tmp = area(i, j, height[i-1], height[j-1]);                if(tmp > ans) ans = tmp;            }        }        return ans;    }};
进一步考虑一下,是不是 O(N^2) 中每个情况都要考虑并检测,能不能省去?

如果有以下情况:某个container,左侧a处挡板高度为 h_a,右侧b处挡板高度为 h_b(h_a > h_b)。此时,固定b处挡板不动,移动a处挡板到 a~b 区间中任何一处都没有意义。因为:

  1. 如果移到的挡板高度高于h_b,则 container 的高度还是由更低的 h_b 决定。同时 container 的宽度变窄;
  2. 如果移到的挡板高度低于h_b,则 container 的高度变得更低,同时 container 的宽度还变窄了
此时,唯一可能在区间内达到更大面积的方法,就是拉高短板。以求通过提高短板的高度从而提高整个 container 的高度,弥补宽度的缩小。
这里还有个问题,如果我的最优值,不在  a~b 区间内怎么办?这样区间内的寻找就无意义了。因此,我们要限制初始区间即为整个区间。然后,每一个的最优搜索,才可以保证最终结果的最优化,不会因为左右分别的移动而遗漏最优值。
class Solution {public:    int area(int i, int j, int ai, int aj)    {        int length = (i - j > 0) ? (i - j) : (j - i);        int width  = (ai > aj) ? aj : ai;        return (length * width);    }        int maxArea(vector<int>& height) {        int size = height.size();        int left = 0, right = size - 1;        int ans  = area(left, right, height[left], height[right]);        while(left < right)        {            if(height[left] < height[right])    left++;            else                                right--;            int tmp = area(left, right, height[left], height[right]);            ans = (ans > tmp)? ans: tmp;        }        return ans;    }};

算法的正确性证明,可以用反证法(传送门)。
也可以这么想:下一个更大的面积,都是从当前状态转变的。而当前状态是去除不可能情况之后逐步遍历得到的,所以不会比之前状态的面积更小,只会更大。所以最终得到的,一定是最大值。

0 0
原创粉丝点击