[LeetCode
来源:互联网 发布:淘宝联盟用了红包丢单 编辑:程序博客网 时间:2024/06/14 08:34
1 问题
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.
2 分析
这道题LeetCode网站中给出的解法为 双指针法,双指针法在处理字符串类的问题中非常常见。这里着重从数学的角度分析该题目的解法。设容器的面积为
题目求的是在不同
下面根据
- 如果
ai≥aj , 移动ai 到ai+1 :- 如果
ai+1≥ai ,那么Si+1,j=Si,j (根据S的公式容易判断) - 如果
ai+1<ai , 那么Si+1,j<Si,j
即在这种情况下,移动ai 一定不会导致Si,j 的面积增加
- 如果
- 如果
ai<aj , 移动ai 到ai+1 :- 如果
ai<ai+1<aj , 那么Si+1,j 的面积有可能大于Si,j - 如果
ai<aj<ai+1 , 那么Si+1,j 的面积一定大于Si,j - 如果
ai+1<ai<aj , 那么Si+1,j 的面积一定小于Si,j
- 如果
根据上述讨论,只有在2.1和2.2的情况下,
3 代码
public class Solution { public int maxArea(int[] height) { int maxarea = 0, l = 0, r = height.length - 1; while (l < r) { maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) l++; else r--; } return maxarea; }}
[1]代码来源于LeetCode: https://leetcode.com/articles/container-most-water/
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Java三大框架搭建
- boost库简单读写xml
- 山东省第八届ACM省赛 J 题(company)
- 偷换windows窗口过程
- Linux 存储管理 缺页中断和页面换入
- [LeetCode
- HDU 1059 Dividing (多重背包二进制优化)
- 数据结构-C++ 迷宫
- [算法]n阶台阶,一次走一步或两步,有多少种走法?
- K-means KNN AND KD-tree
- [C++]图的邻接矩阵、邻接表及其相互转化和邻接表的广度遍历、深度遍历
- JVM(1):Java 类的加载机制
- 【web前端开发】浏览器兼容性处理大全
- Jquery操作元素属性方法总结(attr()、prop())