[leetcode 11]Container With Most Water
2015-06-10 16:22
459 查看
1 题目:
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.
Hide Tags
Array Two Pointers
2 思路:
天资不才,只能想出O(n^2)的方法,好吧,这个闭着眼睛随意想想也能想出来。然后,一个特例就通不过了。
看了看别人的思路,有一种方法O(n)。
https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
详细说明见别人的解说,在草稿纸上结合着画画就出来了。
3 代码
n^2
n
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.
Hide Tags
Array Two Pointers
2 思路:
天资不才,只能想出O(n^2)的方法,好吧,这个闭着眼睛随意想想也能想出来。然后,一个特例就通不过了。
看了看别人的思路,有一种方法O(n)。
https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
详细说明见别人的解说,在草稿纸上结合着画画就出来了。
3 代码
n^2
public int maxArea(int[] height) { int len = height.length; int maxArea = Math.min(height[len-1],height[0])*(len-1); for(int i = len-1; i >= 0 ; i--){ for(int j = 0; j < i; j++){ if(height[j] < height[0]) continue; int min = Math.min(height[i],height[j]); int temp = min * (i-j); if(temp > maxArea){ maxArea = temp; } } } return maxArea; }
n
public int maxArea(int[] height) { int low = 0; int len = height.length; int high = len - 1; int maxArea = 0; while(low < high){ int temp = Math.min(height[low],height[high])*(high-low); if(temp>maxArea){ maxArea = temp; } if(height[low]<height[high]){ low++; }else{ high--; } } return maxArea; }
相关文章推荐
- 贪心 Codeforces Round #173 (Div. 2) B. Painting Eggs
- Failure [INSTALL_FAILED_OLDER_SDK]
- 技术团队如何招聘和管理,如何避免低效率的官僚作风,来看看Airbnb的经验
- Opencv研读笔记:haartraining程序之icvCreateCARTStageClassifier函数详解~
- Factorial Trailing Zeroes-Leetcode
- 人工智能和机器学习领域有哪些有趣的开源项目?
- AWS中国北京区域推出AWS CloudTrail服务
- 解决使用repo下载opencontrail出现的问题
- 申请baidu地图 sdk,获取sha1步骤
- THE DRUNK JAILER
- THE DRUNK JAILER 分类: POJ 2015-06-10 14:50 13人阅读 评论(0) 收藏
- postgres 引起oom问题的 explain 分析。
- int main(int argc,char argv[]) 的问题
- sony vaio 系统系统项
- uva live 4394 String painter 区间dp
- chrome 突然出现 ERR_PROXY_CONNECTION_FAILED
- Datagridview的某些属性again
- TIME_WAIT状态
- NuPIC:一个开源的人工智能平台
- RAID 磁盘阵列的应用