(java)Container With Most Water
2016-02-24 00:52
627 查看
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.
思路:题意是找两个点(i,a[i]),(j,a[j])使(j-i)*min(a[i],a[j])最大,可以使夹逼的方法,
如果height[i]<height[j],,从左往右找一个比height[i]小的height[k],i=k
如果height[i]>height[j] 从右往左找一个比height[j]大的height[k] j=k;
取res=max(res,(j-i)*min(height[i],height[j])),直到i=j为止,得到的就是最大的res
代码如下(已通过leetcode)
public class Solution {
public int maxArea(int[] height) {
int n = height.length;
int i = 0;
int j = n - 1;
int res = 0;
while (i < j) {
res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) {
int k = i;
while (k < j && height[k] <= height[i])
k++;
i = k;
} else {
int k = j;
while (k > i && height[k] <= height[j])
k--;
j = k;
}
}
return res;
}
}
..., 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.
思路:题意是找两个点(i,a[i]),(j,a[j])使(j-i)*min(a[i],a[j])最大,可以使夹逼的方法,
如果height[i]<height[j],,从左往右找一个比height[i]小的height[k],i=k
如果height[i]>height[j] 从右往左找一个比height[j]大的height[k] j=k;
取res=max(res,(j-i)*min(height[i],height[j])),直到i=j为止,得到的就是最大的res
代码如下(已通过leetcode)
public class Solution {
public int maxArea(int[] height) {
int n = height.length;
int i = 0;
int j = n - 1;
int res = 0;
while (i < j) {
res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) {
int k = i;
while (k < j && height[k] <= height[i])
k++;
i = k;
} else {
int k = j;
while (k > i && height[k] <= height[j])
k--;
j = k;
}
}
return res;
}
}
相关文章推荐
- struts2标签与jstl标签的混合使用
- springmvc配置监听
- java学习笔记-Java实现几种常见排序方法
- 编写一个程序,把指定目录下的所有的带.java文件都拷贝到另一个目录中,拷贝成功后,把后缀名是.java的改成.txt。
- 我的java开发总结
- (java)Rotate Image
- 四个流行的Java连接池
- (java)Minimum Path Sum
- Eclipse 多行同时注释的快捷操作
- Expression Language的版本简介
- Java练习 学生信息管理系统简版
- Java练习 学生类
- Java练习 管理类
- java.lang.IllegalArgumentException: Service Inten
- java - socket -客户端
- 阿里云部署Java web项目初体验
- logback与Spring、SpringMVC结合使用教程
- spring profile 使用简略
- Java注解类
- Java生成word/pdf解决方案