20.Container With Most Water

来源:互联网 发布:apache 开源框架 编辑:程序博客网 时间:2024/05/29 16:28

leetcode 11

从这篇博客开始新的LeetCode刷题系列,该系列致力于记录在刷题过程中遇到的困难问题,并给出解答代码和证明过程,基础概念也会偶尔补充更新。

题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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,每个数字代表高度y值,出现的次序i为x值,任取两个点向x轴作垂线,将两条垂线与x轴看作是盛水的容器,求容器最大面积



博主使用了暴力算法并不能ac,即使能够ac也不值得提倡,关键是能否想到复杂度为O(n)的算法

下面是国外网友提供的解答:

public int maxArea(int[] height) {     int len = height.length, low = 0, high = len -1 ;     int maxArea = 0;     while (low < high) {       maxArea = Math.max(maxArea, (high - low) * Math.min(height[low], height[high]));       if (height[low] < height[high]) {         low++;       } else {         high--;       }     }     return maxArea;   }
证明过程:

反证法:假设返回值不是最优解,那一定存在一个更好的解,令最优解的左边界为l,右边界为r。上述算法中当两个指针相遇时停止,所以我们一定遍历过其中一个边界,而没有遍历另外一个,假设遍历了l,在下面两种情况下两个指针会停止:

1.右指针也指到l了

   在这种情况下,右指针从右边遍历过来,一定经过了r,与我们的假设矛盾。

2.右指针指到了一个比l更大的值s,在遇到r之前

   这种情况下指向l的左指针会继续向右移动,这时我们注意到l与s组成的面积已经大于l与r的最优解,与我们的假设矛盾。

综上所述,上述算法已经得到了最优解!

欢迎评论讨论!

原创粉丝点击