LeetCode : Container With Most Water [java]
2016-03-05 20:53
417 查看
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.
思路:高度矮的是短板,从两端向中间搜索。
高的那一端向中间移动没有意义,因为计算面积的高不变(为矮的那端,或者高的那端变得比矮的那端更矮),而宽(j-i)却减少了,面积不可能增加。
因此,哪端矮就向中间搜索。
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.
思路:高度矮的是短板,从两端向中间搜索。
高的那一端向中间移动没有意义,因为计算面积的高不变(为矮的那端,或者高的那端变得比矮的那端更矮),而宽(j-i)却减少了,面积不可能增加。
因此,哪端矮就向中间搜索。
public class Solution { public int maxArea(int[] height) { int size = height.length; int left = 0, right = size - 1; int max = 0; while (left < right) { int minheight = height[left] < height[right] ? height[left] : height[right]; int tmp = minheight * (right - left); max = max > tmp ? max : tmp; if (height[left] < height[right]) left++; else right--; } return max; } }
相关文章推荐
- 循环次数不确定要终止循环的方式
- 20145236 冯佳 《Java程序设计》第1周学习总结
- Java堆内存
- Spring连接mysql数据库错误:Cannot load JDBC driver class '${driver}'
- JAVA常用基础知识点[继承,抽象,接口,静态,枚举,反射,泛型,多线程...]
- 安装JDK,window下为什么要设置环境变量JAVA_HOME、CLASSPATH、PATH??
- Spring进阶之路(6)-抽象Bean与工厂Bean以及获取Bean的id
- java特种兵读书笔记(5-8)——其他并发编程知识
- java类的初始化顺序
- Spring集成Mybatis配置映射文件方法详解
- LRU缓存算法Java实现
- # 20145205 《Java程序设计》第1周学习总结
- java中的集合
- 20145330孙文馨 《Java程序设计》第一周学习总结
- 20145223《Java程序程序设计》第1周学习总结
- javaweb笔记全套
- 学习java的一点心得(一)
- 解决myeclipse中没有filter新建功能+点击Customize Perspective 没有反应
- Java——java.text.SimpleDateFormat的用法
- Spring集成Mybatis错误Result Maps collection already contains value for XXX