LeetCode 0011 - Container With Most Water
# Hints
- 双指针扫描
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
Given non-negative integers , where each represents a point at coordinate . vertical lines are drawn such that the two endpoints of line is at and . 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 is at least .
The above vertical lines are represented by array . In this case, the max area of water (blue section) the container can contain is .
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
# 题意
在平面上有 根柱子,第 根柱子的 坐标为 ,高度为 ,要求选择两根柱子作为水池的左右边界(如图所示),问最多能装多少水。计算盛水体积时不考虑池内柱子的体积。
# 题解
暴力枚举的做法很显然,时间复杂度为 。
注意到问题具有单调性。我们考虑选择最左和最右的 和 两根柱子,不妨设 ,可以发现,如果不改变 的选择,那么另一根无论选什么都不会比选 更优,因为 限制了盛水的高度,而容器的宽度也不会比选 更大。
因此考虑双指针扫描,初始令 ,根据 和 的大小决定下一个被移动的索引,同时更新答案即可。因为 和 都是单向移动,且总移动次数不超过 次,所以时间复杂度为 。
细节问题:
- 注意传入数组为空的情况,要特判,或注意 的初始化细节。
# AC代码
class Solution {
public:
int maxArea(vector<int> & height) {
// 主循环
int res = 0;
int left = 0, right = (int)height.size() - 1;
while (left < right) {
// 更新答案
int area = (right - left) * min(height[left], height[right]);
res = max(res, area);
// 递进
if (height[left] < height[right]) {
left ++;
} else {
right --;
}
}
// 返回
return res;
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01