LeetCode OJ 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.
【思路1】
暴力拆解,找出所有的组合,返回其中最大的。但是这样运行会超时,代码如下:
public class Solution {
public int maxArea(int[] height) {
if(height == null || height.length == 0) return 0;
int max = 0;
for(int i = 0; i < height.length - 1; i++){
for(int j = i + 1; j < height.length; j++){
int minH = Math.min(height[i], height[j]);
max = Math.max(max, (j - i)*minH);
}
}
return max;
}
}
【思路2】
The brute force solution can definitely lead us to the right answer just by doing too many redundant comparisons. When two pointer approach comes to mind, it is intuitive to set both pointers i, j at each end of this array, and move them strategically to the middle of array, update the answer during this process return the answer when we reach the end of array. Suppose now we have the scenarios below:
7, 5, 6, 9 i j
When i = 1, j = 4,
ans = min(7, 9) * (4 - 1) = 21
What's next? Should we move i or j? We notice that to calculate the area, the height is really identified by the smaller number / shorter end between the two ends, since it's required that you may not slant the water, so it sounds like Bucket theory: how much water a bucket can contain depends on the shortest plank. So, as to find the next potential maximum area, we disregard the shorter end by moving it to the next position. So in the above case, the next status is to move i to the left,
7, 5, 6, 9 i j
update:
area (i, j) = area(2, 4) = min(5, 9) * (4 - 2) = 10
ans = max(21, 10) = 21
You may notice that, if we move j instead, you actually get a larger area for length of 2:
area (i, j) = area(1, 3) = min(7, 6) * (3 - 1) = 18
Does that mean this approach will not work? If you look at this way, we move pointer as to get the next potential max, so it doesn't need to be the maximum for all combinations with length l. Even though 18 is greater than 10, it's smaller than 21 right? So don't worry, we can move on to find the next potential maximum result. Now we need to prove, why disregard the shorter end can safely lead us to the right answer by doing a little maths.
Given an array: a1, a2, a3, a4, ai, ......, aj, ......, an
i j
Assume the maximum area so far is ans, we prove that
"By moving shorter end pointer further doesn't eliminate the final answer (with two ends at maxi, maxj respectively) in our process"
Suppose we have two ends at (i, j) respectively at this moment:
(i) If the final answer equals what we have already achieved, it's done! In this scenario, we must have
maxi <= i, maxj >= j
(ii) Otherwise, we know as we move any pointer further, the length of the next rectangle decreases, so the height needs to increase as to result in a larger area. So we have
min(height[maxi], height[maxj]) > min(height[i], height[j])
So the smaller one in height[i], height[j] won't become any end in the maximum rectangle, so it's safe to move forward without it.
Till now, it has been proved that this approach can work in O(n) time since we advance one end towards the middle in each iteration, and update ans takes constant time in each iteration.
代码如下:
public class Solution {
public int maxArea(int[] height) {
int ans = 0;
int i = 0, j = height.length - 1;
while(i < j){
ans = Math.max(ans, (j - i) * Math.min(height[i], height[j]));
if(height[i] > height[j]) j--;
else i++;
}
return ans;
}
}
LeetCode OJ 11. Container With Most Water的更多相关文章
- 《LeetBook》leetcode题解(11):Container With Most Water[M] ——用两个指针在数组内移动
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- 【LeetCode】11. Container With Most Water 盛最多水的容器
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:盛水,容器,题解,leetcode, 力扣,python ...
- 【LeetCode】11. Container With Most Water
题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...
- leetcode problem 11 Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). ...
- Leetcode Array 11 Container With Most Water
题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...
- leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II
11. Container With Most Water https://www.cnblogs.com/grandyang/p/4455109.html 用双指针向中间滑动,较小的高度就作为当前情 ...
- Leetcode 11. Container With Most Water(逼近法)
11. Container With Most Water Medium Given n non-negative integers a1, a2, ..., an , where each repr ...
- LeetCode Array Medium 11. Container With Most Water
Description Given n non-negative integers a1, a2, ..., an , where each represents a point at coordin ...
- leetcode面试准备:Container With Most Water
leetcode面试准备:Container With Most Water 1 题目 Given n non-negative integers a1, a2, ..., an, where eac ...
随机推荐
- mysql 的事务
$conn = mysql_connect('localhost','root','root') or die ("数据连接错误!!!");mysql_select_db('tes ...
- flex属性值----弹性盒子布局
里面的属性都 是在有display: flex的情况 下才生效. 兼容性写法: display: -webkit-box; /*老版本语法: Safari, iOS, Android browse ...
- delphi 快捷键大全
************************* 1.功能键 2.组合键 3.其他快捷键 4.补充 5.补充1(带分类) 6.补充2 --Edit by 2013.1.14 ************ ...
- 搭建gitbook环境
1.官网下载安装nodejs,安装完成后使用终端输入node -v,用cmd命令窗口查看是否安装成功:如下图所示: 2.在cmd命令窗口中输入:npm install -g cnpm -registr ...
- nsstring遍历汉子
NSString *mytimestr=@"好人一生平安"; size_t length = [mytimestr length]; ; i < length; i++) { ...
- Java的设计模式----strategy(策略模式)
设计模式: 一个程序员对设计模式的理解: “不懂”为什么要把很简单的东西搞得那么复杂.后来随着软件开发经验的增加才开始明白我所看到的“复杂”恰恰就是设计模式的精髓所在,我所理解的“简单”就是一把钥匙开 ...
- TheSeventhWeekJavaText
如何用二维数组绘制五子棋盘 在定义一个棋盘类,声明一个二维字符数组,为每一个数组元素赋值为"+",打印输出就是一个简单地棋盘,如下图: 然后定义BufferedReader的实例对 ...
- android studio导入第三方源码模块
从网上得到的但三方源码模块,如果直接导入到自己的项目里的时候,可能需要比较长的时间,甚至不成功. 在导入之间,还是应该将模块里的 build.gradle 编辑一下,使其与自己的android stu ...
- JAVA内容回顾(二)——面向对象(OOP)
1.类与对象 类:类指的是同种对象的抽象,看不见摸不着的.包含有属性与方法. 对象:是类的具体实现,看的见摸得着的东西. 类是对象的抽象,对象是类的具体实现. 2.访问修饰符 public:在项目的任 ...
- Spring.net 学习IOC------准备
在学习spring.net开始时,我们首先要下载spring.net所用到的类库: Common.Logging.dll(必要)Spring.Core.dll(必要)Spring.Data.dllSp ...