算法第十四周解题报告
来源:互联网 发布:查询树形 mysql 编辑:程序博客网 时间:2024/06/06 23:31
问题描述:
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.
解题思路:
设f(p1, p2)为p1、p2点构成的水槽的盛水面积
则我们要求的目标为max(f(0, height.size()-1));
这个问题可以分解为max(f(0, height.size()-1), max(f(p1, p2))), 其中p1、p2 属于集合{p|0 <= p <= height.size() - 1};
另外我们可以知道,若f(p1, p2)不在端点取最大值,则必有min(h[p1], h[p2]) > min(h[0], h[height -1]), 由此我们可以断言,最大值要不然在端点处取得,要不然就在端点构成的区间内某一大于端点最小值的端点上取得,缩小范围后,继续重复上述推理,可得结果,复杂度为O(n)
代码如下:
class Solution {public: int maxArea(vector<int>& height) { int left = 0 , right = height.size() -1 , max=0; int curA; while(left<right) { curA = (right - left) * (height[left] > height[right] ? height[right] : height[left]); if (height[left]<height[right]) { ++left; } else { --right; } max = curA > max ? curA : max; } return max; }};结果如下:
阅读全文
0 0
- 算法第十四周解题报告
- 第十四周程序设计课解题报告
- 第十四周报告
- 第十四周报告2
- C++第十四周报告2
- 第十四周实验报告二
- 第十四周实验报告1
- 第十四周实验报告1
- 第十四周实验报告2
- 第十四周实验报告1
- 第十四周实验报告2
- 第十四周实验报告1
- 第十四周实验报告2
- 第十四周实验报告1
- 第十四周实验报告1.0
- 第十四周实验报告2
- 第十四周实验报告3
- 第十四周实验报告2
- C语言基础之结构体和共用体
- AT91启动打印问题
- Markdownpad2<激活码>
- Nginx配置文件详解
- Fuschia 是什么样的一个操作系统
- 算法第十四周解题报告
- Spring-IoC概念
- 网络获取bitmap
- NetBeans打包报错
- Java知识小结—(3)
- DRML(2016-CVPR)重现过程记录---(9)问题解决与最终结果
- vs快捷键
- 字符串的排列__
- Ubuntu安装anaconda和tensorflow