LeetCode日记–11.Container with most water

发布于 2020-09-23  108 次阅读


碎碎念:这是不知道多久以前的题目了,趁着今天出成绩没心情,把文章补上吧。实训给我七十多分就nm的离谱,毛概也才刚刚好90,怕是保研无望了。

题目如下:

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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

从直觉上来看这题其实很简单,即使用双指针作为左右边界,每次将高度较低的一侧往中间移一位,记录下当前的max area。

但是我们如何从数学上证明这是可行的呢?

首先我们设x为左指针,y为右指针,t为左右指针的距离。为了方便讨论,这里不妨设x<y。

min(x,y)∗t=xt

若我们固定x不动,左移右指针,此时t1<t,那么可以分两种情况讨论:

若y'<y,则min(y',x)≤min(y,x)

若y'≥y,则min(y',x)=x

同时,指针间距又变小了。因此,无论如何在不移动指针对应值较小的指针的情况下,将不会有更大的存储容量出现。

这样算法就很明显了,伪代码如下:

while(left<right){

res = res与当前算出来的容量中较大的

if(左指针对应值小)

左指针右移

else

右指针左移

}

循环结束后返回res

具体代码如下:

class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int leftPointer = 0;
        int rightPointer = n-1;
        int res = Math.min(height[leftPointer],height[rightPointer])*(rightPointer-leftPointer);
        while(leftPointer<rightPointer){
            if(height[leftPointer]<height[rightPointer])
                leftPointer++;
            else
                rightPointer--;
            res = Math.max(res,Math.min(height[leftPointer],height[rightPointer])*(rightPointer-leftPointer));
        }
        return res;
    }
}

你好哇!欢迎来到雷公马碎碎念的地方:)