383. 装最多水的容器

给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai)。画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)(i, 0)。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。

 注意事项

容器不可倾斜。

 

样例

给出[1,3,2], 最大的储水面积是2.

 

看题看了半天,又看了下英文版才看懂

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.

拿样例来说,就是(1, 1), (2, 3), (3, 2) 这三个点与其对应(i, 0)点连成的线。

思路我们可以先想到暴力,所有线两两组合求面积,再选最大的。

但是我们可以注意到,面积取决于

1、两条线中较短的那条

2、两条线之间的距离

第二个比较好解决,我们可以从大到小(两边向内)遍历。

但第一个的话,我们的思路是找到一个大的,再使第二个也尽量大。

如果left>right, 那么我们可以变动right看能不能找到更大的right,否则变动left

计算出来如果比上一个大就替换掉,否则保留

 1 int maxArea(vector<int> &heights) {
 2         // write your code here
 3         int left=0;
 4         int right=heights.size()-1;
 5         int area=0;
 6         while(left<right){
 7             area=max(area,min(heights[left], heights[right])*(right-left));
 8             if(heights[left] > heights[right]){
 9                 right--;
10             }
11             else{
12                 left++;
13             }
14         }
15         return area;
16     }

 

 

posted @ 2017-12-26 05:00  三人木君  阅读(424)  评论(0编辑  收藏  举报