leetcode Container With Most Water

来源:互联网 发布:开淘宝网店视频教程 编辑:程序博客网 时间:2024/06/08 14:35

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.

两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。

这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。

可以做简单证明。

如图,L1<R1<R2<L2,那么在L1移动到L2和R1移动到R2的过程中,存在的Lx和Rx都满足Lx < L1, Rx < R1。假设Lx < Rx,那么Lx* d(Rx - Lx) < L1*d(Rx-Lx) < L1 * ( R1 - L1)。若Lx > Rx,则Rx * d(Rx - Lx) < Rx * d(R1 - L1) < L1 * d(R1 - L1) (因为Rx,Lx都小于L1<R1)。直观的想就是,如果宽度减少,同时左右两侧的板都比原来的还要矮,怎么可能容纳更多的水呢?

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



0 0