11. Container With Most Water
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.
给定n个非负整数a 1,a 2,...,a n,其中每个代表坐标(i,a i)处的一个点。绘制n条垂直线,使得线i的两个端点处于(i,a i)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,使得容器包含最多的水。
注意:你可能不倾斜容器,n至少为2。
(1)思想1:定义 begin=0 和 end=height.size() 两个指针分别指向数组的左右两端,然后两个指针向中间搜索,每移动一次算一个值和结果比较取较大的,容器装水量的算法是找出左右两个边缘中较小的那个乘以两边缘的距离(即矩形的面积)。
C++:
1 class Solution { 2 public: 3 int maxArea(vector<int>& height) { 4 int begin=0,end=height.size()-1; 5 int res=0; 6 while(begin<end) 7 { 8 res=max(res,min(height[begin],height[end])*(end-begin)); 9 if(height[begin]<height[end]) 10 begin++; 11 else 12 end--; 13 } 14 return res; 15 } 16 };