leetcode 11.Container With Most Water
来源:互联网 发布:韩国美女直播秀软件 编辑:程序博客网 时间:2024/05/01 23:20
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坐标(这里下标规定从1开始),求任意两隔板间的最大盛水量。
(短板原理,盛水容量为X坐标之差乘以较小隔板的高度)
高度数组首尾两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。
这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。
面积 area = min(height[j], height[i]) * (j-i),当height[i] < height[j]时,此时面积 area = height[i] * (j-i); 由于height[i]是短板,不管跟谁组合,它能达到的最大面积取决于 j-i,而此时j-i的距离是最大的,因此,此面积即为以i为左边界的最大面积,然后++i;同理得j的变化。因为对于i, j,总有一个是短板,每次是短板的就发生变化,因此覆盖了所有情况。class Solution {public: int maxArea(vector<int>& height) { int max_area = 0; int area = 0; int n = height.size(); int left = 0; int right = n -1; while(left < right) { area = min(height[left],height[right]) * (right - left); if(area > max_area) { max_area = area; } if(height[left] < height[right]) left++; else right--; } return max_area; }};
0 0
- 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
- 从此不求人:自主研发一套PHP前端开发框架(11)
- 拯救频繁跳槽的必杀技!
- MySQL权限篇之LOCK TABLES及元数据锁
- 下拉刷新组件中嵌套ViewPager的一个手势冲突
- DOS命令删除.SVN文件
- leetcode 11.Container With Most Water
- mac下用cornerstone,在update时提示the working copy is locked
- ntpd使用
- Linux入门:VIM
- 动态规划之寻找两个字符串最长公共子串
- hdu 5652 bestcoder 77 div2 2
- Android 6.0 运行时权限处理
- 贪心1008
- Hibernate 集合属性的操作