leetcode第11题
2015-07-24 15:13
274 查看
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.
首先,将两条线设为第一条和最后一条,此时的宽度是最大的。若以后的容器大于这个,只能是高度更高,所以可以更新短的那根线,若第一根线短,则向前推进,只有遇到更高的线时才需要重新计算;若短的是第二根线,则向后推进,遇到更高的线时更新
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea=0;
int i=0;
int j=height.size()-1;
int h=0;
while(i<j)
{
h=min(height[i],height[j]);
maxArea=max(maxArea,h*(j-i));
cout<<maxArea<<endl;
while(height[i]<=h&&i<j)
i++;
while(height[j]<=h&&i<j)
j--;
}
return maxArea;
}
};
int main()
{
Solution sl1;
vector<int> vec{1,2,3,6,5};
cout<<sl1.maxArea(vec)<<endl;
}
..., 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.
首先,将两条线设为第一条和最后一条,此时的宽度是最大的。若以后的容器大于这个,只能是高度更高,所以可以更新短的那根线,若第一根线短,则向前推进,只有遇到更高的线时才需要重新计算;若短的是第二根线,则向后推进,遇到更高的线时更新
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea=0;
int i=0;
int j=height.size()-1;
int h=0;
while(i<j)
{
h=min(height[i],height[j]);
maxArea=max(maxArea,h*(j-i));
cout<<maxArea<<endl;
while(height[i]<=h&&i<j)
i++;
while(height[j]<=h&&i<j)
j--;
}
return maxArea;
}
};
int main()
{
Solution sl1;
vector<int> vec{1,2,3,6,5};
cout<<sl1.maxArea(vec)<<endl;
}
相关文章推荐
- 国内外智慧医疗云平台调研
- using Camel in a Web Application
- using Camel in a Web Application
- php文件上传之多文件上传
- HDOJ 5294 Tricks Device 最短路(记录路径)+最小割
- iWatch报错: Authorization request cancled
- EditText不可编辑
- /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by ./xxxx
- GSMM数据库设计小结
- MYSQL---多表更新
- GitHub: Windows 下的简单使用
- dom、dom 4j解析xml文件
- 千里之行始于足下
- Css3制作变形与动画效果
- 图像处理------基于Otsu阈值二值化
- 图像处理------基于Otsu阈值二值化
- 数据结构各种排序
- cocos2d-x 开发遇到的坑
- perl 通过代理 访问
- omx 使用总结