Leetcode 11. Container With Most Water

来源:互联网 发布:全球最大社交软件 编辑:程序博客网 时间:2024/05/16 09:00

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.

题目大意:有n个长度不一定相等的木板,等间隔排列间隔长度为1,求出两个木板是的它们与x轴围成的矩形(竖直长度选择两个木板中最短值)的最大值。

题目分析:先开始设置头尾两个指标,因为围成的面积大小取决于最短的那个,最长的哪个木板往内移动哪怕找到更长的木板都不行,所以往里移动较短的木板,如果较短的木板长度变长,则面积有可能比原来的大。若比原来的大则记录,否则不记录。

代码如下:

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


0 0
原创粉丝点击