class Solution {
public:
int trap(vector<int>& height) {
int len = height.size();
int i = 0, j = len - 1;
int premax = 0, remax = 0;
int ans = 0;
while (i <= j) {
premax = max(premax, height[i]);
remax = max(remax, height[j]);
if (premax >= remax)
ans += remax - height[j--];//可以储存的水的量
else
ans += premax - height[i++];
}
return ans;
}
};
class Solution {
public:
int trap(vector<int>& height) {
int len = height.size();
int ans = 0;
stack<int> st;
for (int i = 0; i < len; i++) {
while (!st.empty() && height[st.top()] < height[i]) {
int top = st.top();
st.pop();
if (st.empty())
break;
int left = st.top();
int width = i - left - 1;
int hei = min(height[left], height[i]) - height[top];
ans += hei * width;
}
st.push(i);
}
return ans;
}
};
func trap(height []int) int {
n := len(height)
PreMax := make([]int, n + 1)
NeMax := make([]int, n + 2)
for i := 0; i < n; i ++ {
PreMax[i + 1] = max(PreMax[i], height[i])
}
for i := n - 1; i >= 0; i -- {
NeMax[i + 1] = max(NeMax[i + 2], height[i])
}
ans := 0
for i := 0; i < n; i ++ {
ans += min(PreMax[i + 1], NeMax[i + 1]) - height[i]
}
return ans
}
双指针
想了一下也写出来了
func trap(height []int) int {
ans, PreMax, ReMax, i, j := 0, 0, 0, 0, len(height) - 1
for i <= j {
PreMax = max(PreMax, height[i])
ReMax = max(ReMax, height[j])
if PreMax > ReMax {
ans += ReMax - height[j]
j --
} else {
ans += PreMax - height[i]
i ++
}
}
return ans
}
栈
栈还是没想出来咋做,唉唉
func trap(height []int) int {
n := len(height)
ans := 0
var stk []int
for i := 0; i < n; i ++ {
for len(stk) != 0 && height[stk[len(stk) - 1]] < height[i] {
top := stk[len(stk) - 1]
stk = stk[:len(stk) - 1]
if len(stk) == 0 {
break
}
left := stk[len(stk) - 1]
wid := i - left - 1
hei := min(height[i], height[left]) - height[top]
ans += wid * hei
}
stk = append(stk, i)
}
return ans
}