题解
执行用时:8 ms, 在所有 C++ 提交中击败了69.41%的用户
内存消耗:13.9 MB, 在所有 C++ 提交中击败了54.33%的用户
-
分治思路。
首先我们要找到[left,right]中最高的那个柱子的位置记为maxIndex,把它作为last。
什么叫last?我们下面体会一下。
下面我们只需要在[left,maxIndex-1]中找到最高的柱子,位置记为leftIndex,在[maxIndex+1,right]中找到最高的柱子,位置记录为rightIndex,我们这个时候可以res+=leftIndex到maxIndex中间可以装的水+maxIndex到rightIndex中间可以装的水 两个部分。
找到了之后呢,我们把last设置为leftIndex和rightIndex,代表这是求解[left,leftIndex-1]和[rightIndex+1,right]这两个范围内的最大值了。
也就划分产生了子问题。
这里有点讲不清,讲的清楚的话需要大量笔墨,可以看代码,也就是[left,right]的大问题划分成了两个小问题,[left,leftIndex-1]和[rightIndex+1,right]。
-
时间复杂度分析
每次计算[left,right]内的最大值时间复杂度为O(n),因为每次扫描找最大值都可能做了重复的工作,实际应该大于O(n),但是相当于每次是二分的分割数组,一般来说划分的深度为logn, 所以不会大于 O ( n l o g n ) O(nlogn) O(nlogn),这个区间查询最大值可以用线段树优化,可以降低这部分复杂度。
-
空间复杂度大抵和时间复杂度的分析类似,实际也类似。
代码
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int res;
int n;
int findMax(int left, int right, vector<int>& height) {
int maxVal = -1;
int maxIndex = -1;
for (int i = left; i <= right; i++) {
if (height[i] > maxVal) {
maxVal = height[i];
maxIndex = i;
}
}
return maxIndex;
}
int getSum(int left, int right) {
return _prefixSum[right + 1] - _prefixSum[left];
}
// 初始时候last==-1代表这个时候我们需要先求出[left,right]范围中的最大值
// 只有开始需要求一下[left,right]范围内的最大值
// 后面的话,把已经求的的最大值最为last参数传递就可以了
void solve(int left, int right, int last, vector<int>& height) {
if (left >= right) {
return;
}
int maxIndex;
if (last == -1) {
maxIndex = findMax(left, right, height);
}
else {
maxIndex = last;
}
int leftIndex = -1, rightIndex = -1;
if (left <= maxIndex - 1) {
leftIndex = findMax(left, maxIndex - 1, height);
}
if (maxIndex + 1 <= right) {
rightIndex = findMax(maxIndex + 1, right, height);
}
// cout<<left<<" "<<right<<" "<<leftIndex<<" "<<rightIndex<<" "<<maxIndex<<" "<<res<<endl;
if (leftIndex != -1) {
res += (height[leftIndex] * (maxIndex - leftIndex - 1)) - getSum(leftIndex + 1, maxIndex - 1);
}
if (rightIndex != -1) {
res += (height[rightIndex] * (rightIndex - maxIndex - 1)) - getSum(maxIndex + 1, rightIndex - 1);
}
if (leftIndex != -1 && left < leftIndex - 1) {
solve(left, leftIndex - 1, leftIndex, height);
}
if (rightIndex != -1 && rightIndex + 1 < right) {
solve(rightIndex + 1, right, rightIndex, height);
}
}
vector<int>_prefixSum;
void getPrefixSum(vector<int>& height) {
_prefixSum.resize(height.size() + 1);
_prefixSum[0] = 0;
int n = height.size();
for (int i = 0; i < n; i++) {
_prefixSum[i + 1] = _prefixSum[i] + height[i];
}
}
int trap(vector<int>& height) {
// 返回值
res = 0;;
n = height.size();
// 计算前缀和数组,因为我们要根据两个数字之前比如4,5之间所有数字的和4和5之前产生的空挡的差来计算我们当前4和5包裹的范围内可以存多少的水
getPrefixSum(height);
// 递归求解
solve(0, n - 1, -1, height);
cout << res << endl;
return res;
}
};
// int main() {
// vector<int>inP({ 4,2,0,3,2,5 });
// //inP.resize(6);
// Solution sol;
// sol.trap(inP);
// }