[Leetcode] container with most water 最大水容器
2024-08-27 17:12:50
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.
题意:数组的值为容器的高度,下标之差为容器的宽度,求最大面积
思路:这题其实和3sum closest类似,从数组的两端,向中间遍历,计算最大面积,然后将高度较小的那端向前递进一个就行。如:3 5 8 7 6 2;开始时,面积为2*(5-0)=10;然后,尾端前进一个单位,面积为3*(4-0)=12;依次类推,取面积的最大值即可。时间的复杂度为O(n)代码如下:
class Solution {
public:
int maxArea(vector<int> &height)
{
int l=,r=height.size()-;
int mArea=;
while(l<r)
{
mArea=max(mArea,(r-l)*min(height[l],height[r]));
height[l]<height[r]?l++:r--;
}
return mArea;
}
};
还有一种常规的思路:就是使用两个指针,一个固定,另一个从第一个的后面一个开始不断的向后遍历,求最大的面积;然后 移动第一个,第二重复上述操作。这种思路用两个for循环。但时间的复杂度为O(n^2)。
最新文章
- hrbrid需要做的
- [Xamarin] 客製化的ListView之章 (转帖)
- qt练习10 涂鸦板源代码
- 多种css3时尚侧栏菜单展开显示效果Off-Canvas Menu Effects
- [转] JavaScript中的属性:如何遍历属性
- CSS动画:Transform中使用频繁的scale,rotate,translate动画
- BNU10804:域名统计
- opencv----人脸美白算法,祛斑,祛痘,磨皮等
- C++ 11 学习1:类型自动推导 auto和decltype
- java:数组操作工具类 java.util.Arrays包 主要方法详解
- 使用requireJS
- HDU - 1495 bfs [kuangbin带你飞]专题一
- 聊天斗图神器aidou mac中文版
- javascript高级程序设计第3版——第5章 引用类型
- postMan测试https接口
- win7 64位下redis的安装
- Log4J基础详解及示例大全(转)
- css 手机适配
- Linux下MyCat和MyCat_web的安装和配置
- ECharts.js 简单示例