Leetcode: Trapping Rain Water

题目

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

思路:

1. 以前在 leetcode 上做过一道题叫做 candy, 这道题类似, 那道题的精髓在于从左到右和从右到左两遍扫描

2. 使用堆栈记录一个槽的左右 index, 然后统计其可存放的雨水

3. (2) 的方法不能统计高度递减的槽, 因此还需要一次从右向左的扫描

4. 代码中的 queue 和 stack 都是一种东西, 名字不同而已

代码:

class Solution {
public:
    int trap(int A[], int n) {
		if(n <=2)
			return 0;

		deque<int> queue;
		int sum = 0;
		for(int i = 0; i < n; i ++) {
			if(queue.empty() || A[i] <queue[0]) {
				queue.push_back(A[i]);
			}else{ // 容器的另一半
				while(!queue.empty()) {
					sum += queue[0]-queue.back();
					queue.pop_back();
				}
				queue.push_back(A[i]);
			}
		}
		// reverse last part
		deque<int> stack;

		for(int i = queue.size()-1; i >= 0; i-- ) {
			if(stack.empty() || queue[i] < stack[0]) {
				stack.push_back(queue[i]);
			}else{
				while(!stack.empty()) {
					sum += stack[0]-stack.back();
					stack.pop_back();
				}
				stack.push_back(queue[i]);
			}
		}
		return sum;
    }
};

  

原文地址:https://www.cnblogs.com/xinsheng/p/3510543.html