leetcode解题方案--011--Container With Most Water
来源:互联网 发布:网盘 数据库 编辑:程序博客网 时间:2024/06/18 01:00
题目
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 and n is at least 2.
例如 8 4 9 6 3 7 1 应为8和7组成的容器,答案为35.
分析
暴力解法:这种思想很想求直方图下方最大矩形面积。直方图的思想是以每个ai为最低点,求出左侧边界和右侧边界,对每一项算出其面积,再取最大。
这道题的想法就是,以每个a[i]为边界中较短的那一条边。求最大面积,就是从0开始找到大于等于a[i]的,再从length-1开始找到第一个大于等于a[i]的。两者取最大。最后,在所有的面积中取最大。
此方法会超时
代码块
public static int maxArea0(int[] height) { int[] result = new int[height.length]; int max = 0; int length = height.length; for (int i = 0; i <length; i++) { int left = 0; int right = 0; for (int k1 = 0; k1 < i; k1++) { if (height[k1] >= height[i]) { left = height[i]*(i-k1); break; } } for (int k2 = length-1; k2 > i; k2--) { if (height[k2] >= height[i]) { right = height[i]*(k2-i); break; } } int tmp = left>right?left:right; if (tmp>max) { max = tmp; } } return max;
分析
用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。
public static int maxArea1(int[] height) { int max = 0; int length = height.length; for (int i =0, j = length-1; j-i>=1;) { if (height[j] >=height[i]) { int tmp = height[i] * (j-i); if (max < tmp) { max = tmp; } i++; }else { int tmp = height[j] * (j-i); if (max < tmp) { max = tmp; } j--; } } return max; }
阅读全文
0 0
- leetcode解题方案--011--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 javascript解题]Container With Most Water
- [LeetCode] Container With Most Water 解题报告
- 【LeetCode】Container With Most Water 解题报告
- leetcode-011:Container With Most Water
- LeetCode 011 Container With Most Water
- LeetCode 011 Container With Most Water
- [LeetCode]-011-Container With Most Water
- leetcode 011 Container With Most Water
- LeetCode-011 Container With Most Water
- LeetCode 011 Container With Most Water
- 【LeetCode OJ 011】Container With Most Water
- [LeetCode]011-Container With Most Water
- unity生成怪物
- CSS —— 继承body 确保最高优先级
- WebStorm 打开Node.js的代码提示功能
- MySQL数据库主从同步
- webservice用main方法发布https接口
- leetcode解题方案--011--Container With Most Water
- 讲真,你真的懂JDBC吗?
- 菜鸟日常错误之点击Run直接跳到子活动界面而不是主活动
- Frida官方手册
- 详解iOS11、iPhone X、Xcode9 适配指南
- 影响数据库性能的因素以及解决方法
- 比特币老兵
- Unity3d灯光问题-一个模型上添加太多灯光出现问题
- 第四周【项目5