leetcode 42:Trapping Rain Water

来源:互联网 发布:波士顿矩阵 编辑:程序博客网 时间:2024/05/19 12:18

题目:

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!

思路:

可以用左右两个指针来指示,如果左边最大(leftMax)小于右边最大(rightMax),则从左边开始计算,容量加上左边最大减去对应高度。反之,则从右边开始,容量加上右边最大减去对应高度。

当然如果有nums[left]>leftMax,则需要更新最大值。

直到左边指针大于右边指针。

时间复杂度:O(n)

实现如下:

class Solution {public:int trap(vector<int>& height) {int size = height.size();if (size < 2) return 0;int result=0;int left = 0, right = size - 1;int maxLeft=0, maxRight=0;while (left <= right){if (height[left] <= height[right]){if (height[left] > maxLeft) maxLeft = height[left];else result += maxLeft - height[left];left++;}else{if (height[right] > maxRight) maxRight = height[right];else result += maxRight - height[right];right--;}}return result;}};


0 0
原创粉丝点击