【LeetCode】11. Container With Most Water
来源:互联网 发布:蒙文软件免费下载 编辑:程序博客网 时间:2024/06/06 18:57
Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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 andnis at least 2.
题意
给定的是垂直于x轴的直线,让你求出两条直线,使得跟x轴围成的面积最小。
所以问题转换为一个矩形一条边取纵坐标小的那根,一条边取横坐标的差值,求这个矩形的面积最大(一开始以为是梯形,明显不合逻辑)。
答案
我自己想了半天的思路是,从前往后遍历,找每个以height[i]为高的矩形的最大值,遍历n次即可。
定义two pointer,一个是m=0,一个是n=size-1,找到第一个比当前 height[i]大的值(++m;--n),此时max(i-m,n-i)*height[i]肯定是以height[i]为高的矩形的最大值。比较n个取最大即为所得。这个时间复杂度还是o(n^2),但是有剪枝,所以通过了。
.但后来翻答案发现还有更简单的思路,就是以底边长遍历,two pointer,一个是m=0,一个是n=size-1,第一次就已经把min(m,n)为边的面积算出来了。然后对m,n小的边进行移动,又算出了以m-1为高的矩形的值
class Solution {public: int maxArea(vector<int>& height) { int max=0; for(int i=0;i<height.size();i++){ int m=0,n=height.size()-1; while(m<i&&height[m]<height[i]) m++; while(n>i&&height[n]<height[i]) n--; int tmp=height[i]*((i-m>n-i)?i-m:n-i); if(tmp>max1) max=tmp; } return max; }};
class Solution {public: int maxArea(vector<int>& height) { int max=0; int m=0,n=height.size()-1; while(m<n){ int tmp=min(height[m],height[n])*(n-m); max=tmp>max?tmp:max; if(height[m]<height[n]) m++; else if(height[m]>height[n])--n; else {++m; --n;} } return max; }};
- 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] 11. Container With Most Water
- [leetcode] 11.Container With Most Water
- 【leetcode】11. Container With Most Water
- [LeetCode]11. Container With Most Water
- 11. Container With Most Water LeetCode
- leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- [LeetCode OJ]11. 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 11. Container With Most Water
- LeetCode *** 11. Container With Most Water
- 在Servlet中直接调用Spring的getBean引起的HTTP Status 500
- 2027
- 对ac自动机的一些个人理解
- cordova的安装与配置
- 数据结构上机测试1:顺序表的应用
- 【LeetCode】11. Container With Most Water
- 2028
- 资金流入流出预测-挑战Baseline
- OJ -1272 写数游戏 求助指导
- Sysbench出图
- 2029
- 一维数组名与二维数组名的差别
- OAuth2
- 2030