前言
今天看了灵茶修艾府算法精讲第二讲,好牛
11.盛最多水的容器
看图,可以看出来,如果左边比右边柱子高,则高度是由右边柱子决定,接下来就需要循环,为了寻找最高,我们要让右边往前移动,而不是让左边往右移动,因为左边柱子已经相比最高,在间距变短条件下,如果右边柱子高度增加,可能面积会比之前大,代码如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int ans = 0, left = 0, right = n - 1;
while (left < right) {
int area = (right - left) * max(height[left], height[right]);
ans = max(ans, area);
if (height[left] > height[right]) {
right --;
} else {
left ++;
}
}
return ans;
}
};
42.接雨水
方法一:前后缀分解法
一列分为左边和右边,都是这一列的索引是一样,我们要把左边称为前缀,右边称为后缀。
这道题,每个有水的地方,都是这个区域的 min(前缀 - 后缀) - 柱子高
前缀求法: 从左到右循环,如果改区域前缀比前一个区域前缀高,则该区域前缀是本身;如果矮,则是之前高的前缀。这样就可以防止漏出去
后缀求法: 同理
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size(), ans = 0;
vector<int> pre_max(n);
pre_max[0] = height[0];
for (int i = 1; i < n; i++) {
pre_max[i] = max(pre_max[i - 1], height[i]);
}
vector<int> suf_max(n);
suf_max[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
suf_max[i] = max(suf_max[i + 1], height[i]);
}
for (int i = 0; i < n; i++){
ans += min(pre_max[i], suf_max[i]) - height[i];
}
return ans;
}
};
上述方法时间复杂度为O(n),空间复杂度为O(n)。
方法二:双向指针法
从头的前缀和尾的后缀开始比较,如果前缀矮,则水就是前缀减去头的柱子高度,然后头向后移动。
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size(), ans = 0;
int left = 0, right = n - 1;
int pre_max = 0, suf_max = 0;
while (left <= right) {
pre_max = max(pre_max, height[left]);
suf_max = max(suf_max, height[right]);
if (pre_max < suf_max) {
ans += pre_max - height[left];
left ++;
} else {
ans += suf_max - height[right];
right --;
}
}
return ans;
}
};
这个需要多理解,时间复杂度为O(n),空间复杂度为O(1)。