Leet Code 11 Container With Most Water
2015-09-10 21:38
579 查看
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.
思路:利用一个性质,ai右边更小的边ak (k > i) 与 aj (j > k) 之间的面积一定比ai,aj围成的面积更小。
..., 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.
思路:利用一个性质,ai右边更小的边ak (k > i) 与 aj (j > k) 之间的面积一定比ai,aj围成的面积更小。
public int maxArea(int[] height) { if(height.length <= 1) { return 0; } int left = 0; int right = height.length - 1; int maxArea = right * ( height[left] < height[right] ? height[left] : height[right]); int tmpArea = 0; while(left < right) { tmpArea = (right - left) * ( height[left] < height[right] ? height[left] : height[right]); maxArea = tmpArea > maxArea ? tmpArea : maxArea; if(height[left] < height[right]) { int k = left; while((k < right) && (height[k] <= height[left])) { k ++; } left = k; } else { int k = right; while((k > left) && (height[k] <= height[right])) { k --; } right = k; } } return maxArea; }
相关文章推荐
- Container With Most Water
- http://jingyan.baidu.com/article/08b6a591f0fafc14a9092275.html
- linker command failed with exit code 1 错误的解决
- POJ 1840 Brainman(逆序对数)
- Package的Transaction处理之一:使用Connetion的属性RetainSameConnection
- httpd: Could not reliably determine the server's fully qualified domain name
- email program (客户端)演变过程有感
- Email发展历史
- 多线程中让main方法最先开始,最后结束的简单例子
- baiduPOP3/SMTP设置
- wait和nofity
- vector make_pair
- 真机调试的时候出现no identity foundCommand /usr/bin/codesign failed with exit code 1
- async与await
- HDU-3394 Railway
- delegate为什么用ASSIGN 而不是retain
- Email附件下载流程分析
- 一个rails项目连多个mongo数据库
- copy,assign,strong,retain,weak,readonly,nonatomic的区别
- 一个rails项目连多个mongo数据库