leetcode-42. 接雨水
class Solution { public: int trap(vector<int>& height) { vector<int> left(height.size(),0); vector<int> right(height.size(),0); int lefttemp = 0; int righttemp = 0; // 最左边的接不了雨水 for(int i = 1; i < height.size(); i++){ lefttemp = max(lefttemp, height[i-1]); left[i] = lefttemp; // left[i] 记录当前i左边的最大值 } // 最右边的接不了雨水 for(int i = height.size()-2; i >=0; i--){ righttemp = max(righttemp, height[i+1]); right[i] = righttemp; // right[i] 记录当前i右边的最大值 } int res = 0; // 注意两头的不用判断,肯定接不了雨水 for(int i = 1; i < height.size()-1;i++){ int minval = min(left[i],right[i]); if(minval>height[i]) res = res + (minval - height[i]); } return res; } };
基于上一个进一步 优化,一遍循环
class Solution { public: int trap(vector<int>& height) { int left_max = 0; int right_max = 0; int left = 0; int right = height.size()-1; int res = 0; /* 定理二:当我们从左往右处理到left下标时,左边的最大值left_max对它而言是可信的, 但right_max对它而言是不可信的。 定理三:当我们从右往左处理到right下标时,右边的最大值right_max对它而言是可信的, 但left_max对它而言是不可信的。 */ while(left<right){ left_max = max(height[left],left_max); // 记录到left(包括left)位置的左边最大值 right_max = max(height[right], right_max); // 记录到left(包括left)位置的左边最大值 if(left_max < right_max){ res = res + (left_max-height[left]); // 如果left(包括left)位置的左边最大值等于height[left] // 显然left_max-height[left]等于0,不能存水, // 但也可能left_max大于height[left],此时可以存水。 left++; } else{ res = res + (right_max-height[right]); right--; } } return res; } };