Container With Most Water
来源:互联网 发布:ubuntu卸载自带输入法 编辑:程序博客网 时间:2024/05/16 12:18
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 linei 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.
题的意思也很好理解。容量=min(ai, aj)*(j-i)。
1)O(N^2)的算法
class Solution {public: int maxArea(vector<int>& height) { //int i=0, j=0;int maxV=0;for(int i=0; i<height.size(); ++i) {for(int j=i+1; j<height.size(); ++j) {int Vol=min(height[i], height[j])*(j-i);if(Vol > maxV) {maxV = Vol;}}}return maxV; }};
2)O(N):如果最值点取在ai,aj,则aj的右侧不会有比aj更高的点。若有的话,设为ak,则min(ai,ak)*(k-i)比min(ai,aj)*(j-i)大,矛盾。同理ai的左侧也不会有比ai高的点。所以若我们已经得到两个候选点ai和aj,比候选更优的点只能在(i,j)范围内且其高度高于ai和aj。所以可以从两侧向内遍历,但是要注意的是每一个循环中哪一侧往内缩进,从上述推理可以得出要缩进的是ai和aj中的较低者。比如ai=2,aj=3时,i要执行i++,因为ai和(i, j)内的所有的点组成的面积都要小于和aj的。
class Solution{public:int maxArea(vector<int> &height) {int left=height[0], right=height[height.size()-1];int i=0, j=height.size()-1;int maxV=min(height[i], height[j])*(j-i);while(i<j) {if( height[i] > left || height[j] > right) {int tempV=min(height[i], height[j])*(j-i);if(tempV > maxV) {maxV = tempV;left=i;right=j;}}if(height[i] <= height[j])++i;else --j;}cout<<left<<" "<<right<<endl;return maxV;}};
0 0
- Container With Most Water
- Container with most water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- 输出Bag中的所有记录为一个只有值的json数组---精通android、IOS App应用服务程序开发
- LeetCode——Add Two Numbers
- ftps
- HDOJ 1465 不容易系列之一(错排公式)
- Activity类
- Container With Most Water
- Aurora协议调研
- ios (推送)之本地推送
- 【android】只有小时和分钟的弹出式时间选择器
- 边做游戏边学android—7(塔防②创建目标)
- hiho一下 第四十八周题目1 : 拓扑排序·二
- cocos关于内存方面的文章
- Android之异步线程原理
- 基于v4l2的摄像头驱动笔记