LeetCode :: Container With Most Water
来源:互联网 发布:淘宝提交多个订单 编辑:程序博客网 时间:2024/06/05 17:44
题目如下:
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,j),计算出maxArea,时间复杂度O(N2)。
二、思考一下,从两端开始往中间遍历,设i = 0, j = height.size() - 1; 由于是短板决定计算出的面积大小,所以当让坐标往中间走的时候(宽度是递减的),必须移动短的一端。这样才有希望让面积增大,不然的话,由于短板限制,面积肯定随着宽度的减少而递减。
代码如下:
class Solution {public: int maxArea(vector<int> &height) { int area = 0, Max = 0; int i = 0, j = height.size() - 1; while (i < j){ if (height[i] > height[j]){ area = height[j] * (j - i); j--; } else{ area = height[i] * (j - i); i++; } if (area > Max) Max = area; } return Max; }};
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
- 黑马程序员-C语言基础学习(五)
- 23. 微软面试题:跳台阶问题
- 摄像头 由于其配置信息(注册表中的)不完整或已损坏,Windows 无法启动这个硬件设备。 (代码 19)
- 2014Android开发热门资料(110个)
- 关于Linux 系统下 C++ 的多线程基类 Thread
- LeetCode :: Container With Most Water
- WPF ListBoxItem模板中添加CheckBox选中问题
- Linux上JDK、Eclipse的安装
- 网络视频监控P2P解决方案
- Qt 游戏之路(一) 场景搭建 和 战车移动、地图拉伸
- 简单Struts2实例(入门级)
- 1006. Sign In and Sign Out
- MVC学习笔记八:WebGrid控件的高级使用
- 002_005 Python 计算一个文件中有多少行即读取文件行数