用C++单调栈写接雨水
时间: 2023-03-22 19:01:52 浏览: 94
好的,以下是用C语言单调栈写接雨水的代码:
```c
int trap(int* height, int heightSize){
int ans = 0, current = 0;
int stack[heightSize];
int top = -1;
while(current < heightSize){
while(top != -1 && height[current] > height[stack[top]]){
int h = height[stack[top]];
top--;
if(top == -1){
break;
}
int distance = current - stack[top] - 1;
int min_height = fmin(height[stack[top]], height[current]) - h;
ans += distance * min_height;
}
top++;
stack[top] = current;
current++;
}
return ans;
}
```
这个算法使用了单调栈,时间复杂度为O(n),空间复杂度为O(n),其中n为height数组的长度。