0042. 接雨水 #49
utterances-bot
started this conversation in
Comments
Replies: 3 comments
-
附C++代码附上动态规划的解法,左右数组 const int N = 2e4+5;
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int leftMax[N] = {0};
int rightMax[N] = {0};
for(int i = 1; i < n-1; ++i)
leftMax[i] = leftMax[i-1] > height[i-1] ? leftMax[i-1] : height[i-1];
for(int i = n-2; i > 0; --i)
rightMax[i] = rightMax[i+1] > height[i+1] ? rightMax[i+1] : height[i+1];
int res = 0, minheight;
for(int i = 1; i < n-1; ++i) {
minheight = leftMax[i] <= rightMax[i] ? leftMax[i] : rightMax[i];
if(minheight > height[i]) res += (minheight-height[i]);
}
return res;
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
-
附C++代码,使用的最简单的双指针方法,方法为 盛最多水的容器 接雨水 class Solution {
public:
int trap(vector<int> &height) {
int ans = 0;
int l = 0, r = height.size() - 1;
int pre_max = 0, suf_max = 0;
while(l <= r){
pre_max = max(pre_max, height[l]);
suf_max = max(suf_max, height[r]);
if(pre_max < suf_max){
ans += pre_max - height[l];
l++;
}
else{
ans += suf_max - height[r];
r--;
}
}
return ans;
}
}; 方法时间复杂度为 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0042. 接雨水 | 算法通关手册
https://algo.itcharge.cn/Solutions/0001-0099/trapping-rain-water/
Beta Was this translation helpful? Give feedback.
All reactions