Leetcode-container-with-most-water
来源:互联网 发布:仓库管理php源码 编辑:程序博客网 时间:2024/06/10 02:48
题目描述
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组成的木桶容积大。
0 0
- 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
- LeetCode:Container With Most Water
- Ubuntu常用翻译工具——星际译王StarDict
- eclipse 轻松NDK开发
- 记沪江之行
- 关于android系统Binder机制解析
- 安装oracle12c后,用dbca建数据库老遇到ora-12560错误的解决策
- Leetcode-container-with-most-water
- 键盘移动div样例
- 275. H-Index II
- Spring bean 设值注入和 构造注入
- springmvc controller ajax 一些使用说明
- SimpleNet网络框架源码分析
- 银行家算法的实现,有关进程资源分配的算法
- spring 2 bean配置--基本配置
- java.util.ConcurrentModificationException错误