Leetcode -- Container With Most Water
来源:互联网 发布:软件售后分那些 编辑:程序博客网 时间:2024/05/22 08:06
题目:
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.
分析:若干条线,找两条线使得其与X轴围成的面积最大。
如果是暴力的穷搜,肯定可以得到答案,但复杂度达到O(N^2),耗时,leetcode里面是过不去的。
思路:从数据集的两头同时开始。当ai小于aj时,i ++; 反之,j–。直到二者相遇。理由,影响面积的是比较短的线,因此,每次只要改变比较短的线就好了。这个想法的复杂度是O(N)
代码:
int maxArea(vector<int>& height) { int len = height.size(); int max_area = 0, area = 0; int i = 0, j = len - 1; while(i < j) { if(height[i] < height[j]) { area = (j -i) * height[i]; i ++; } else { area = (j - i) * height[j]; j --; } if (area > max_area) { max_area = area; } } return max_area; }
0 0
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode-Container With Most Water
- Container With Most Water leetcode
- LeetCode - Container With Most Water
- LeetCode: Container With Most Water
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- LeetCode:Container With Most Water
- 几种还款的方式中本金和利息的计算
- NSIS 小问题
- 自定义控件三:自定义属性
- 火星上发生的事情与Vxworks操作系统的优先级反转问题
- xcode7 真机调试
- Leetcode -- Container With Most Water
- 贝叶斯推断及其互联网应用(二):过滤垃圾邮件
- android之屏幕适配之深入研究
- BroadcastReceiver监听网络状态
- POJ 2516 Minimum Cost(最小费用最大流-mcmf)
- HDOJ 1102 Constructing Roads(最小生成树--prime)
- 随机颜色
- 橡皮擦
- IO复用,select、poll、epoll综述