题目描述:

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.

本题给我们a1、a2……an相当于二维坐标系上的纵坐标,而它们在数组中的下标就是横坐标。过每个点作与x轴垂直的线段相当于“木桶壁”,本题问的是哪两个“木桶壁”能装最多的水,返回最大面积。

解题思路:

本题我的思路是先用left和right记录最左和最右的“木桶壁”的下标,比较它们的大小,小的往中心移动一格。每次都比较下它们组成的面积和最大面积。

代码:

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         int left=0,right=height.size()-1,max=0;
 5         while(right>left){
 6             int area=(height[left]<height[right]?height[left]:height[right])*(right-left);
 7             max=area>max?area:max;
 8             if(height[left]>height[right])
 9                 right--;
10             else
11                 left++;
12         }
13         return max;
14     }
15 };

 

 

 

posted on 2018-02-22 21:27  宵夜在哪  阅读(97)  评论(0编辑  收藏  举报