首页 > 代码库 > Leetcode:Container With Most Water

Leetcode: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.

 

解题思路:

首先当然可以想到的是暴力解,复杂度为O(n^2) 不出意外,是超时的。

这个题有点巧妙的是在于 容器盛水时的瓶颈问题。假设容器左右两端 x坐标分别为 first 和 last,这两个坐标向中间移动,移动的过程中就可以包含所有容器的情形。

容器盛水的体积 v = min(afirst ,alast) * (last - first)  (容器不能是类似于梯形那样的)

当 afirst <= alast 时,我们如果将 last 向左移动,无论 alast 的值是如何的,容器盛水的体积肯定是减小的,因为这时瓶颈在于 afirst(因为是较小值),

并且 向左移动时 last - first 也是减小的, 这是我们如果想增大容器体积,只能是将 first 向右移动

当 afirst > alast 时的情形与上面类似,暂略。

此解法复杂度为O(n)

class Solution {
public:
    int maxArea(vector<int> &height) {
       int currArea = 0;
       int maxArea = 0;
       int first = 0;
       int last = height.size() - 1;
       while (first < last) {
           currArea = min(height.at(first), height.at(last)) * (last - first);
           maxArea = max(maxArea, currArea);
           if (height.at(first) <= height.at(last)) {
               first++;
           } else {
               last--;
           }
       }
       return maxArea;
    }
};