Leetcode-container-with-most-water
2016-06-27 16:39
351 查看
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.
我采用的就是暴力搜索的方法,复杂度o(n^2),感觉不是太好。
看了一下别人的做法,用贪心算法解决,感觉是好一些。
public static int maxArea(int[] height) {
int result=0;
if(height.length<=1) return result; //无法构成容器
int i=0,j=height.length-1;
while(i<j){
int area = (j-i)*Math.min(height[i],height[j]);
if(area>result)result = area;
if(height[i]>height[j]){
j--;
}else{
i++;
}
}
return result;
}
合理性解释:当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, ...)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。
题目描述
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.
我采用的就是暴力搜索的方法,复杂度o(n^2),感觉不是太好。
public static int maxArea(int[] height) { int max = -1; int res = 0; for(int i=0; i<height.length-1; i++){ for(int j=i+1; j<height.length; j++){ if(height[i] >= height[j]){ res = height[j] * (j-i); }else{ res = height[i] * (j-i); } if(res > max) max = res; } } return max; }
看了一下别人的做法,用贪心算法解决,感觉是好一些。
public static int maxArea(int[] height) {
int result=0;
if(height.length<=1) return result; //无法构成容器
int i=0,j=height.length-1;
while(i<j){
int area = (j-i)*Math.min(height[i],height[j]);
if(area>result)result = area;
if(height[i]>height[j]){
j--;
}else{
i++;
}
}
return result;
}
合理性解释:当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, ...)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。
相关文章推荐
- http://blog.csdn.net/wangkehuai/article/details/45057811
- win8系统蓝屏提示DRIVER POWER STATE FAILURE的原因及两种解决方法
- POJ1273 Drainage Ditches 【最大流】
- Leetcode-climbing-stairs
- svn post-commit hook faild(exit code 1) with output /Username not found 错误
- Paint之函数大汇总
- activemq调优
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATIBLE解决办法
- LightOJ 1038 Race to 1 Again
- 【error】LINK1123: failure during conversion to COFF: file invalid or corrupt
- Mongo运行错误:Failed to connect 127.0.0.1:27017,reason:errno:10061由于目标计算机积极拒绝,无法连接
- 【NOIP2013模拟联考5】军训(training)
- Memblaze发布企业级数据存储管理系统FlashRAID——从NVMe SSD出发,全面进击软件定义存储
- saiku源码整合(无maven情况下)
- ssrs 2016, mobile report error: The report may be misconfigured, the data may not be available, or the server version may be unsupported.
- ADB server didn't ack * failed to start daemon及unable to obtain result of 'adb versio错误
- 利用 hadoop 的 FileSystem open 方法获取 FSDataInputStream 实现文件下载到本地 Hadoop 版本 2.7.0
- AIX命令
- AIDL实现应用间通信
- wait,notify,notifyAll简单介绍