leetcode 151: Container With Most Water
来源:互联网 发布:protty网络验证 编辑:程序博客网 时间:2024/06/07 06:49
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 linei 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. brute force ( O(n^2)) 超时.
2. i,j 间 不共享重复的SUBCASE. 不适合使用Dynamic Programming.
3. greedy 方法适用.
//因为i是短板,所以如果无论j往前移动到什么位置,都不可能产生比area更大的面积 //换句话所,i能形成的最大面积已经找到了,所以可以将i向前移。 [1]
public class Solution { public int maxArea(int[] height) { int sz = height.length; int max = 0; int l=0, r=sz-1; while(l<r) { int area = (r-l) * Math.min(height[l], height[r]); max = max>area? max:area; if(height[l]<height[r]) { ++l; } else { --r; } } return max; }}
Reference:
[1] http://blog.unieagle.net/2012/09/16/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Acontainer-with-most-water/
0 0
- leetcode 151: Container With Most Water
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] 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
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- PHP及Javascript 正则判断中文
- hdu 4871 Shortest-path tree(最短路+点分治)
- poj_1979 Red and Black
- javascript源码阅读推荐
- MYSQL数据库恢复记录
- leetcode 151: Container With Most Water
- 威威猫系列故事――打地鼠
- 海水淡化膜:海水淡化反渗透膜预处理工艺的重要性
- Mac 下配置 Cocos2d-x 3-x android 的环境,terminal 和 eclipse两种方式
- hpu 2098 素数拆分
- java多线程面试题
- crm使用soap删除记录
- android UI 之自定义组合空间
- SpringMVC 4 配置返回JSP,和Freemarker视图