【leetcode】Array——Container With Most Water(11)
2016-03-21 21:07
465 查看
题目: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.
思路:本以为和之前的题目:Largest Rectangle in Histogram解题思路一样,细想也不是。参考了leetcode的解法:https://leetcode.com/discuss/59635/easy-concise-java-o-n-solution-with-proof-and-explanation也许这个解法不好理解,还可以看看这个:https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
总结一下思路:
两个指针:left=0 right=height.length-1 。假如left=0,right=6:
如果height[left]<height[right],则0-5 0-4 … 0-1 都要比0-6小(准确来说是不可能比0-6大),所以left++。
如果height[left]>height[right],则1-6 2-6 … 5-6 都要比0-6小(准确来说是不可能比0-6大),所以right--
代码:
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.
思路:本以为和之前的题目:Largest Rectangle in Histogram解题思路一样,细想也不是。参考了leetcode的解法:https://leetcode.com/discuss/59635/easy-concise-java-o-n-solution-with-proof-and-explanation也许这个解法不好理解,还可以看看这个:https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
总结一下思路:
两个指针:left=0 right=height.length-1 。假如left=0,right=6:
如果height[left]<height[right],则0-5 0-4 … 0-1 都要比0-6小(准确来说是不可能比0-6大),所以left++。
如果height[left]>height[right],则1-6 2-6 … 5-6 都要比0-6小(准确来说是不可能比0-6大),所以right--
代码:
public int maxArea(int[] height) { int left=0,right=height.length-1; int max=0; while(left<right){ max = Math.max(max, Math.min(height[left], height[right])*(right-left)); if(height[left]<height[right]) left++; else right--; } return max; }
相关文章推荐
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- Aizu 2450 Do use segment tree 树链剖分
- hdu1022Train Problem I
- hdu 1151 Air Raid DAG最小路径覆盖
- Rails中使用邮箱验证及激活用户
- Dsamain
- rails 路由设置 无法匹配 小数点
- rails中select_tag的用法小结
- rails调试
- Rails插件之ckeditor
- Rails插件之byebug
- LeetCode 70 Climbing Stairs
- 简单AIDS的源码学习 <utils.c>
- [LeetCode]-DataBase-Delete Duplicate Emails
- strong,weak,assign,retain,copy区别与联系
- [LeetCode]-DataBase-Duplicate Emails
- async & await 的前世今生
- async 和 await 的异步处理
- Traits技术初探
- 循环 retain 问题