Leetcode 42. Trapping Rain Water 发表于 2019-12-01 | 分类于 Online Judge https://leetcode.com/problems/trapping-rain-water/ 第一种解法是单调栈 1234567891011121314151617181920212223242526272829303132class Solution {public: int trap(vector<int>& height) { // 边界情况判定 if(height.size() < 2){ return 0; } stack<int> s; int res = 0; int cur = 0; while(cur < height.size()){ //栈内的元素是单调递增的 while(!s.empty() && height[cur] > height[s.top()]){ // 当遍历的到元素比当前栈顶元素值大时,计算此时的蓄水量 int top = s.top(); s.pop(); if(s.empty()){ break; } int dist = cur - s.top() - 1; int bound = min(height[cur], height[s.top()]) - height[top]; res += dist * bound; } s.push(cur++); } return res; }}; 第二种解法是双指针 1234567891011121314151617181920212223242526class Solution {public: int trap(vector<int>& height) { if(height.size() < 2){ return 0; } int res = 0; int length = height.size(); // 分别从头和尾开始的指针 int left = 0, right = length - 1; int left_max = 0, right_max = 0; while(left < right){ if(height[left] < height[right]){ height[left] >= left_max ? left_max = height[left] : res += left_max - height[left]; left++; } else{ height[right] >= right_max ? right_max = height[right] : res += right_max - height[right]; right--; } } return res; }}; 本文作者: Moon 本文链接: 2019/12/01/Leetcode-42/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!