LeetCoder_____Container With Most Water(11)
来源:互联网 发布:python for openwrt 编辑:程序博客网 时间:2024/05/20 17:25
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 and n is at least 2.
题意:
给出一个序列a1,a2,a3......an,每个数字ai表示在(i,0)(i,ai)之间有木杆,也就是一共有n个竖直木杆。我们选取其中两根木杆跟x轴可以构成一个凹形容器,问整个容器体积最大为多少?也就是求:Max(min(ai,aj)*abs(i-j)).
分析:
很显然如果使用两重循环,枚举两根木杆,很简单就可以解决这个问题。但是时间复杂度是O(n^2)。
所以我们需要换一种思路。
假设一开始两根木杆选取最左和最右。无论最优解为何值,我们只要将最左木杆右移,最右木杆左移,总能达到。
但是,是应该让最左木杆右移还是最右木杆左移呢?我们知道无论是left ++还是right -- ,对于abs(right - left) 值都是不变的。
变化的是min(aleft,aright)。所以根据贪心的思想,我们只需要判断left,right对应的两根木头哪个比较短,就移动哪个。然后不断更新最大值。
代码:
class Solution {public: int maxArea(vector<int>& height) { int left,right,ans; left = 0,right = height.size() - 1; ans = min(height[left],height[right])*(right-left); while(left<right){ if(height[left]<height[right]){ left ++; }else{ right --; } if(min(height[left],height[right])*(right-left)>ans)ans = min(height[left],height[right])*(right-left); } return ans; }};
- LeetCoder_____Container With Most Water(11)
- 11、Container With Most Water
- 11、Container with most water
- #11 Container With Most Water
- 11 Container With Most Water
- 11 Container With Most Water
- 11 Container With Most Water
- [11]Container With Most Water
- 【11】Container With Most Water
- 11 container with most water
- 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
- 最长连续数字子串
- C++利用链表与模板实现栈
- POJ2559 POJ2082 POJ3494(最大矩形面积 单调栈)
- 转接IC NCS8803:HDMI转EDP芯片
- Spring 框架的 BeanFactory 和 ApplicationContext 简述
- LeetCoder_____Container With Most Water(11)
- BZOJ1085 [SCOI2005]骑士精神
- 性能调优之:缓存
- ssh免密登录配置
- dubbo多服务结点+zookeeper集群
- TCP/IP 入门
- PAT 1128
- OpenGL ES 学习难点日志
- zookeeper实例