042 - Trapping Rain Water

来源:互联网 发布:同花顺官方炒股软件 编辑:程序博客网 时间:2024/06/09 15:30

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!



int findleft(int *height, int size, int loc){if (height[loc - 1] <= height[loc]) return -1;else return loc - 1;}int findright(int *height, int size, int loc){int i, right = -1;for (i = loc + 1; i < size; i++) {if ((height[i] > height[loc]))if (right < 0)right = i;else if (height[i] > height[right])right = i;if (height[right] >= height[loc - 1]) break;}return right;}int trap(int* height, int heightSize) {int i, j, left, right;int ret = 0;for (i = 1; i < heightSize - 1; i++) {left = findleft(height, heightSize, i);right = findright(height, heightSize, i);if (left >= 0 && right > 0) {int h = height[left] < height[right]? height[left]:height[right];for (j = left + 1; j < right; j++) {ret += h - height[j];}i = right;}}return ret;}


0 0
原创粉丝点击