11. Container With Most Water

来源:互联网 发布:软件企业评估管理办法 编辑:程序博客网 时间:2024/05/16 17: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 and n is at least 2.

翻译

给定n个非负整数12,...,n,其中每个表示坐标(ii处的点绘制n条垂直线,使得线i的两个端点在(ii)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,使得容器含有最多的水。

注意:您不能倾斜容器,n至少为2。

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

分析

做了一段时间leetcode,现在看见vector就想排序,不过这题不能排序

本题可以用一个maxarea储存每一次的水容量,并在这次的循环中通过MAX函数与上一次的容量相比较

而水容量等两条线段中较短的乘以两条线的距离   

循环的关键条件在于,每一次循环变动的边应该是较短的那条



0 0
原创粉丝点击