【LeetCode】【Python解读】Container with most water
2015-07-16 11:25
701 查看
这个问题是芭芭拉在采访中遇到的,不幸的是,的复杂性O(n2)该,太失望了,难怪没有通过面试。
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.
题目说的有点复杂,大意是利用x轴作底,两个随意的竖直线段作杯壁,何时盛水最多。
木桶原理大家肯定都知道,水盛多少取决于最短的杯壁,所以此题还能够引申为往围成的区域内放矩形。如何使得矩形面积最大。
题目中的不能倾斜(slant:倾斜,倾倒)相应为矩形必须水平放置。
复杂度为O(n)的思想是贪心原理,先从底边最大的情况考虑,计算最大面积后。此时要将底边长度减1,仅仅须要将杯壁较短的那一边移动一个单位距离,得到的解必然优于杯壁较长那边移动的情况。这样保证每次移动都得到的是局部最优解。
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.
题目说的有点复杂,大意是利用x轴作底,两个随意的竖直线段作杯壁,何时盛水最多。
木桶原理大家肯定都知道,水盛多少取决于最短的杯壁,所以此题还能够引申为往围成的区域内放矩形。如何使得矩形面积最大。
题目中的不能倾斜(slant:倾斜,倾倒)相应为矩形必须水平放置。
复杂度为O(n)的思想是贪心原理,先从底边最大的情况考虑,计算最大面积后。此时要将底边长度减1,仅仅须要将杯壁较短的那一边移动一个单位距离,得到的解必然优于杯壁较长那边移动的情况。这样保证每次移动都得到的是局部最优解。
class Solution { public: int maxArea(vector<int> &height) { int Len = height.size(),low=0,high=Len-1; int maxV = 0; while(low<high){ maxV = max(maxV,(high-low)*min(height[low],height[high])); if (height[low]<height[high]) low++; else high--; } return maxV; } };
相关文章推荐
- Python的Django框架中的Context使用
- Java,php,python,js 定义常量
- 【Python】文件读写操作
- Java,php,python,js 定义多行字符串
- python在windows通过安装模块错误
- Python学习之跨越篇
- Python学习之环境篇
- Java,php,python,js 定义字符串
- python 字典的setdefault方法
- Python学习之开头篇
- 【Python】遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题
- Java,php,python,js 注释
- ZH奶酪:Python中zip函数的使用方法
- Java,php,python,js 变量
- Python 实现RMI
- Python常用机器学习扩展包
- ZH奶酪:Python中range和xrange的区别
- Nim连接到Python
- Google's Python Class(一)——Python 介绍
- Python开发入门与实战9-基于vs的集成开发环境