【leetcode】Array——Container With Most Water(11)
来源:互联网 发布:数据与标志的关系 编辑:程序博客网 时间:2024/06/06 07:26
题目: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--
代码:
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;}
- 【leetcode】Array——Container With Most Water(11)
- LeetCode(11)——Container With Most Water
- 刷LeetCode(11)——Container With Most Water
- LeetCode——Container With Most Water
- leetcode——Container With Most Water
- Container With Most Water——LeetCode
- leetcode——Container With Most Water
- LeetCode——Container With Most Water
- Container With Most Water —— Leetcode
- leetcode——Container With Most Water
- LeetCode——Container With Most Water
- LeetCode——Container With Most Water
- LeetCode(11) Container With Most Water
- LeetCode (11)Container With Most Water
- leetcode—Container With Most Water
- Leetcode/array/Container With Most Water
- leetcode.array--11. Container With Most Water
- leetcode——11——Container With Most Water
- 获取cell中按钮的交互事件
- cygwin 安装 ffplay
- 阿里云 2016 实习生一、二面
- 使用Apache Phoenix 实现 SQL 操作HBase【包括部分软件安装】
- Hive官方手册学习(二)Hive数据定义语言DDL
- 【leetcode】Array——Container With Most Water(11)
- 框架学习:hibernate框架的结构和分析
- java语言程序设计第十版(Introduce to java 10th) 课后习题 chapter6-30
- hdu 1074 Doing Homework(状态压缩dp)
- 回溯法
- java 自动装箱(面试题)基本知识总结即简例
- linux基础(四)
- poj1002
- shell EOF 用户自定义终止符