【数组】Container With Most Water
2016-01-15 23:46
337 查看
题目:
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.
思路:
两个下标变量,分别表示数组的头部和尾部,逐步向中心推移。这个推移的过程是这样的:
假设现在是初始状态,下标变量i=0表示头部,下标变量j=height.size(),表示尾部,那么显然此时的容器的装水量取决一个矩形的大小,这个矩形的长度为j-i,高度为height[i]与height[j]的最小值(假设height[i]小于height[j])。接下来考虑是把头部下标i向右移动还是把尾部下标j向左移动呢?如果移动尾部变量j,那么就算height[j]变高了,装水量依然没有变得更大,因为短板在头部变量i。所以应该移动头部变量i。也就是说,每次移动头部变量i和尾部变量j中的一个,哪个变量的高度小,就把这个变量向中心移动。计算此时的装水量并且和最大装水量的当前值做比较。
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.
思路:
两个下标变量,分别表示数组的头部和尾部,逐步向中心推移。这个推移的过程是这样的:
假设现在是初始状态,下标变量i=0表示头部,下标变量j=height.size(),表示尾部,那么显然此时的容器的装水量取决一个矩形的大小,这个矩形的长度为j-i,高度为height[i]与height[j]的最小值(假设height[i]小于height[j])。接下来考虑是把头部下标i向右移动还是把尾部下标j向左移动呢?如果移动尾部变量j,那么就算height[j]变高了,装水量依然没有变得更大,因为短板在头部变量i。所以应该移动头部变量i。也就是说,每次移动头部变量i和尾部变量j中的一个,哪个变量的高度小,就把这个变量向中心移动。计算此时的装水量并且和最大装水量的当前值做比较。
/** * @param {number[]} height * @return {number} */ var maxArea = function(height) { var res=0,l=0,r=height.length-1; while(l<r){ res=Math.max((r-l)*Math.min(height[l],height[r]),res); if(height[l]>height[r]){ r--; }else{ l++; } } return res; };
相关文章推荐
- Codeforces Gym 100231F Solitaire 折半搜索
- Syntax error, annotations are only available if source level is 1.5
- vector pair sort
- 2.7 过程表示
- 2.5 框架表示
- Daily Scrum – 1/15
- [POJ 2010]Moo University - Financial Aid[优先队列]
- AIX 6.1 新建fs出错
- 对意识的思考--我--机器人--程序--人工智能
- hive drop table报错:FAILED: SemanticException MetaException(message:Timeout when executing method: g
- Containers Reserved yarn resourcemanager
- 严重: Failed to initialize end point associated with ProtocolHandler ["http-bio-8080"]
- http://blog.csdn.net/enuola/article/details/7917221
- .net4.0切换2.0时,SplitContainer”的对象强制转换为类型
- Rails 4中document.ready失效
- Paint获取Text的宽和高的数据
- Spark学习之键值对(pair RDD)操作(3)
- Spark学习之键值对(pair RDD)操作(3)
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- 全本一六年一月再论人工智能