lintcode刷题——装最多水的容器
来源:互联网 发布:mac文件排序 编辑:程序博客网 时间:2024/06/05 07:56
给定 n 个非负整数 a1, a2, ..., an, 每个数代表了坐标中的一个点 (i, ai)
。画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)
和(i, 0)
。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。
注意事项
容器不可倾斜。
给出[1,3,2]
, 最大的储水面积是2
.
1、首先想到的最笨的办法就是双重循环,出水面积就是两个点中的ai较小的值乘以两个点的下标的差值;
2、双重循环显然时间复杂度太高,这时想到用两个指针一头一尾向中间靠拢,若依旧使用两个for循环来做时间复杂度依旧不满足条件;
3、考虑用一个while循环,加上一个判断条件,就是装水的多少受限于短的一条线,于是加上判断,保留两者之中较长的一条线。
具体C++代码如下所示:
class Solution {
public:
/*
* @param : a vector of integers
* @return: an integer
*/
int maxArea(vector<int> heights) {
// write your code here
int l=heights.size();
if(l==0||l==1)
return 0;
int watermax=0;
int i=0,j=l-1;
/* for(i=0;i<l;i++)
{
int lheight=heights[i];
int li=i;
for(j=l-1;j>i;j--)
{
watermax=max(min(lheight,heights[j])*(j-i),watermax);
}
}*/注释部分为两个for循环代码,时间超过限制
while(i<j)
{
watermax=max(min(heights[i],heights[j])*(j-i),watermax);
if(heights[i]<heights[j])
{
i++;
}
else
{
j--;
}
}
return watermax;
}
};
- lintcode刷题——装最多水的容器
- LintCode-装最多水的容器
- lintcode-装最多水的容器-383
- LintCode:装最多水的容器
- lintcode,装最多水的容器
- Lintcode 装最多水的容器
- Lintcode 装最多水的容器
- LintCode:M-装最多水的容器
- 装最多水的容器-LintCode
- [LintCode 383] 装最多水的容器(Python)
- 装最多水的容器
- 装最多水的容器
- 装最多水的容器
- 装最多水的容器
- 装最多水的容器
- LintCode_383_装最多水的容器
- Java实现-装最多水的容器
- leetcode笔记—容纳最多水的容器
- windows服务启动一个当前用户的进程
- 深入浅出es6之箭头函数
- 动态规划专题之最大连续子序列之和
- IP问问:为什么“我”总是“被”定在天安门?
- 注册谷歌账户Gmail提示:此电话号码无法用于进行验证的解決方法
- lintcode刷题——装最多水的容器
- 字符串匹配的KMP算法
- 这几天的烦恼
- hdu 2188 简单巴什博奕
- LeetCode-108-Convert Sorted Array to Binary Search Tree(转化已排序数组到二叉排序树)
- neupy 时间序列信号处理
- 腾讯校招软件测试工程师题库
- FZU
- HEVC代码学习21:xTZSearch函数