Leetcode Container With Most Water
来源:互联网 发布:插画软件 编辑:程序博客网 时间:2024/06/06 00:51
原题意思是:
给定n个非负整数并记为ai,a2,,,,an,将下标i可以看成X轴横坐标,值ai看成纵坐标,与X轴会形成面积不一样的矩形,任意两条这样的线段和 x 轴组成一个木桶矩形,找出能够盛水最多的木桶,返回其面积。
注意面积大小S=min(ai,aj)|i-j|
最简单方法,暴力求解,时间复杂度O(n^2)
int maxArea1(vector<int> height){int n=height.size();int i,j;int max=0;for(i=0;i<n;i++) for(j=i+1;j<n;j++) {int tmp=min(height[i],height[j])*(j-i);if(tmp>max){max=tmp;continue;} }return max;}提交超时!
用两个指针从两端开始向中间靠拢,如果:
1 左端线段短于右端,此时设左端线段长L,右端线段长R,当出现L<R时,说明该L线段与其他右端线段组成的矩形肯定要小于L与R组成的矩形,因为此时R第一次大于L,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大,故直接i++即左端右移,;
反之右端左移,(类似分析)
直到左右两端移到中间重合,并且记录这个过程中每一次组成木桶的容积,返回其中最大的。
int maxArea(vector<int> height){int n=height.size();int max=0;int i=0,j=n-1;while(i<j){ int tmp=min(height[i],height[j])*(j-i); if(height[i]<height[j])i++; else j--; if(max<tmp){max=tmp;} }return max;}
时间复杂度O(n)。AC!
0 0
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode-Container With Most Water
- Container With Most Water leetcode
- LeetCode - Container With Most Water
- LeetCode: Container With Most Water
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- LeetCode:Container With Most Water
- 配置arm-linux-gcc教程以及可能遇到的问题
- SQL中的n+1次select语句查询问题
- 深入理解计算机第一章总结
- c++环境配置
- php 正则表达式匹配中文字符
- Leetcode Container With Most Water
- poj3617 Best Cow Line
- C/C++中的日期和时间
- npm下载错误解决办法
- Qt动态分配内存的内存回收规则
- python函数中*args和**kwargs的区别
- OpenSSL之EVP(一)——数据结构及源码结构介绍
- 301、404、200、304等HTTP状态
- 初识Python