用栈实现雨滴问题
雨滴问题可以通过栈来解决,具体实现如下:
-
定义一个栈,用来存储雨滴的位置。
-
从左到右遍历数组,如果当前位置的高度小于等于栈顶位置的高度,将当前位置的下标入栈。
-
如果当前位置的高度大于栈顶位置的高度,则说明当前位置左边存在比它高的位置,需要将栈顶位置出栈,计算当前位置和新的栈顶位置之间的水量。具体计算方法为:当前位置和新的栈顶位置之间的距离乘以它们之间较低的高度。
-
重复步骤2和3,直到遍历完整个数组。
-
返回计算出的水量。
以下是具体实现的代码:
int trap(vector<int>& height) {
int n = height.size();
int ans = 0, current = 0;
stack<int> st;
while (current < n) {
while (!st.empty() && height[current] > height[st.top()]) {
int top = st.top();
st.pop();
if (st.empty()) break;
int distance = current - st.top() - 1;
int bounded_height = min(height[current], height[st.top()]) - height[top];
ans += distance * bounded_height;
}
st.push(current++);
}
return ans;
}
时间复杂度:O(n),其中n为height数组的长度。
空间复杂度:O(n),栈的最大长度为n。
原文地址: https://www.cveoy.top/t/topic/bHnv 著作权归作者所有。请勿转载和采集!