题目:
给定 n个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)
//暴力 int trap(vector<int>& height) { int ans = 0; int size = height.size(); for (int i = 1; i < size - 1; i++) { int max_left = 0, max_right = 0; //左边最大值 for (int j = i; j >= 0; j--) { //Search the left part for max bar size max_left = max(max_left, height[j]); } //右边最大值 for (int j = i; j < size; j++) { //Search the right part for max bar size max_right = max(max_right, height[j]); } ans += min(max_left, max_right) - height[i]; } return ans; } //动态编程 int trap(vector<int>& height) { if (height == null) return 0; int ans = 0; int size = height.size(); vector<int> left_max(size), right_max(size); //把左边最大值和右边最大值不放在循环内部求解 left_max[0] = height[0]; for (int i = 1; i < size; i++) { left_max[i] = max(height[i], left_max[i - 1]); } right_max[size - 1] = height[size - 1]; for (int i = size - 2; i >= 0; i--) { right_max[i] = max(height[i], right_max[i + 1]); } for (int i = 1; i < size - 1; i++) { ans += min(left_max[i], right_max[i]) - height[i]; } return ans; } //栈的应用,将数组元素代入就能明白过程 int trap(vector<int>& height) { int ans = 0, current = 0; stack<int> st; while (current < height.size()) { //当前元素大于栈顶元素 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; } //代入值 int trap(vector<int>& height) { int left = 0, right = height.size() - 1; int ans = 0; int left_max = 0, right_max = 0; while (left < right) { if (height[left] < height[right]) { height[left] >= left_max ? (left_max = height[left]) : ans += (left_max - height[left]); ++left; }else { height[right] >= right_max ? (right_max = height[right]) : ans += (right_max - height[right]); --right; } } return ans; }