LeetCode 11. Container With Most Water

来源:互联网 发布:国际数据流量怎么开通 编辑:程序博客网 时间:2024/06/05 03:24

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

找两根线 (i,ai),(j,aj) 与X轴围成一个容器,使得这个容器可以装最多的水。
直接遍历是 O(n2) 的计算复杂度,注意水的高度由最短板决定,可以找到 O(n) 计算复杂度的方法。(代码里把vector转成了array,其实可以不用;vector变array也可以通过修改参数实现,百度一下或者去看看别人的代码)。

class Solution {public:    int maxArea(vector<int>& height) {        int len = height.size();        vector<int>::iterator iter;        int a[len],i,j,temp,ans=0;        for(i=0,iter=height.begin();iter!=height.end();i++,iter++){            a[i]=*iter;        }        i=0;j=len-1;        while(i<j){            temp=(a[i]<a[j]?a[i]:a[j])*(j-i);            ans=ans>temp?ans:temp;            if(a[i]>a[j]) j--;            else i++;        }        return ans;    }};
原创粉丝点击