算法第十四周解题报告

来源:互联网 发布:查询树形 mysql 编辑:程序博客网 时间:2024/06/06 23:31

问题描述:

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.

解题思路:

设f(p1, p2)为p1、p2点构成的水槽的盛水面积

则我们要求的目标为max(f(0, height.size()-1));

这个问题可以分解为max(f(0, height.size()-1), max(f(p1, p2))), 其中p1、p2 属于集合{p|0 <= p <= height.size() - 1};

另外我们可以知道,若f(p1, p2)不在端点取最大值,则必有min(h[p1], h[p2]) > min(h[0], h[height -1]), 由此我们可以断言,最大值要不然在端点处取得,要不然就在端点构成的区间内某一大于端点最小值的端点上取得,缩小范围后,继续重复上述推理,可得结果,复杂度为O(n)


代码如下:

class Solution {public:    int maxArea(vector<int>& height) {        int left = 0  , right = height.size() -1 , max=0;        int curA;         while(left<right) {              curA = (right - left) * (height[left] > height[right] ? height[right] : height[left]);              if (height[left]<height[right]) {                  ++left;              } else {                  --right;              }            max = curA > max ? curA : max;        }          return max;      }};
结果如下: