LeetCode 11 Container With Most Water
来源:互联网 发布:淘宝产品没有3c认证 编辑:程序博客网 时间:2024/06/02 06:16
题意:
数组A中第i个元素A[i]表示一块两端在(i,0)和(i,A[i])的板,从中选出2块板,使得它们与x轴围成的桶装水体积最大。
思路:
因为装水体积只和矮的板有关,因此我们从高到低的考虑板子,这样当前考虑的板子A[i]就是装水的高度。
高度确定时,让桶尽量的宽。可以用l和r表示已经考虑过的板子的x坐标的最小和最大值。
若l <= i <= r,则桶宽max( i - l, r - i );若i < l,则桶宽r - i;若i > r,则桶宽i - l。
时间复杂度O(nlogn)。
官方题解中的O(n)做法是错误的,解法没有覆盖所有的可能,有点类似“用贪心策略做dp而漏解”。
代码:
//// Created by house on 1/9/17.//class Solution {public: int maxArea(vector<int> &height) { int ans = 0; vector <pair<int, int>> rank; for (int i = 0; i < height.size(); ++i) { rank.push_back(make_pair(height[i], i)); } sort(rank.begin(), rank.end()); int l, r; l = r = rank.rbegin()->second; for (int i = rank.size() - 2; i >= 0; --i) { int pos = rank[i].second, w = 0; if (pos < l) { w = r - pos; l = pos; } else if (pos > r) { w = pos - l; r = pos; } else { w = max(r - pos, pos - l); } if (ans < w * rank[i].first) { ans = w * rank[i].first; } } return ans; }};
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
- leetcode 11 Container With Most Water
- leetcode-11 Container With Most Water
- Container With Most Water - LeetCode 11
- [Leetcode 11, Medium] Container With Most Water
- 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-11Container With Most Water
- leetcode 11 -- Container With Most Water
- @RequestMapping注解的详细解释
- Android端使用WebView注入一段js代码实现js调用android
- Android底部/顶部滑动菜单SldMenu
- Websocket一个持久化网络通信的协议
- 漫谈DB选型
- LeetCode 11 Container With Most Water
- python 输入语句以及格式化输出语句的使用
- 剖析Disruptor:为什么会这么快?(二)神奇的缓存行填充
- Git初级入门
- 几个MATLAB函数的用法
- redis学习五,redis集群搭建及添加主从节点
- Android如何判断是否在后台运行
- Windows Server 2008 r2系统安全学习日记 — shadow security scanner
- 什么是面向对象