LeeCode-------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个非负整数a1, a2, ..., an, 每一个整数代表在坐标上的一个点(i, ai)。绘制n条垂直的线,使得线的两端位于 (i, ai) 和 (i, 0)。找到两条线,它们与x轴围成一个容器,能装最多的水。
注意:你不能倾斜容器,并且n至少是2.
分析:
如果用两个for循环,会超时,这里不再赘述。
由于要装水,所以容器能装多少水取决于最短的那一条线段。为了快速计算出面积,我设计两个指针,一个从数组最左边开始向右移动,一个从数组最右边开始向左移动。
创建一个变量,用来存储最大的面积。
每移动一次,就计算一下当前的面积,如果比最大的面积大,就替换最大面积。
如果左边线段比右边短,则左指针向右移,因为面积取决于最短线段,那么左指针向右移可能出现比当前左边线段更长的甚至比当前右边更长的线段,面积可能更大。
同理,如果右边线段比左边短,则右指针向左移动。
如果两个线段相等,则左指针向右移动或者右指针向左移动都可以,因为当前的面积已经计算过了。
当两个指针相遇,返回最大面积。
时间复杂度为O(n).
【Java代码】如下:
class Solution { public int maxArea(int[] height) { int left = 0, right = height.length - 1, area = 0; do{ //计算当前面积 int now = ((right - left) * (height[left] < height[right] ? height[left] : height[right])); //比较当前面积和保存的最大面积,保存最大面积 area = now > area ? now : area; if(height[left] < height[right]){ left ++; }else{ right --; } }while(left <= right);//当左右指针相遇结束 return area; } }
如果有任何问题,欢迎跟我联系:xiaomenxiaomen@qq.com
我的github地址:github.com/WXRain