【LeetCode】Container With Most Water 解题报告
来源:互联网 发布:js定时器控制动画效果 编辑:程序博客网 时间:2024/04/28 21:39
【题目】
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, ai) 表示 从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积。
两层 for 循环的暴力法会超时,所以尽早放弃这种懒惰的想法。
有没有 O(n) 的解法?
答案是有,用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。(想想这样为何合理?)
public class Solution { public int maxArea(int[] height) { if (height.length < 2) return 0; int ans = 0; int l = 0; int r = height.length - 1; while (l < r) { int v = (r - l) * Math.min(height[l], height[r]); if (v > ans) ans = v; if (height[l] < height[r]) l++; else r--; } return ans; }}
合理性解释:当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, ...)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。
1 3
- [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] 11. Container With Most Water 解题报告
- 【LeetCode】11. Container With Most Water 解题报告
- [Leetcode] 11. Container With Most Water 解题报告
- leetcode解题报告11. Container With Most Water
- [LeetCode 解题报告]011.Container With Most Water
- LeetCode 11. Container With Most Water解题报告
- LeetCode Problem 11 Container With Most Water解题报告
- 【LeetCode】11.Container With Most Water(Medium)解题报告
- [leetcode javascript解题]Container With Most Water
- 【LC解题报告】11. Container With Most Water
- LeetCode #11 Container With Most Water 最大容器 解题小节
- 新手学Android【四】问题一<running android lint has encountered a problem>
- 解决ListView的onItemClickListener无响应的问题
- 内存对齐
- sql2008评估已过期问题
- DHCP
- 【LeetCode】Container With Most Water 解题报告
- Hadoop大象之旅007-配置Hadoop伪分布模式
- 主流地图 坐标系转换,百度、腾讯、高德等
- php读书笔记
- 成长就是一种磨练
- 查看Eclipse版本号及各个版本区别
- Android中eclipse等常用工具软件下载
- 《Java7程序设计》第24章 并发工具
- NYOJ 260、263、264