leetcode 42. Trapping Rain Water

来源:互联网 发布:数控编程指令 编辑:程序博客网 时间:2024/06/02 23:06

实习面试时被问的题。。。原来在这里。。。
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.
先画了个图
这里写图片描述
虽然很丑 但是我觉得比方格更容易看懂
嗯 觉得我有点头疼
首先找到“峰值” 即局部最高点ABCDEF
其中最高的是F
从A开始看 B比A矮 接着走 C比A高 停 AC之间的水位高度取决于短板A算一下这段的水量(A的高度*AC距离 - 这段中山占的面积)
从C接着走 D跳过(比C矮) E跳过(比C矮) F比C高 停下 这一段的水位高度取决于短板C 算一下这段的水量(C的高度*CF距离-这段中山占的面积)
F后面可能还有更高的山 可能没有 如果有要一直找更高的点 如果没有情况比较麻烦 所以一开始要先遍历一遍所有山顶 找出最高的山峰 (假设我们已经确定了F是最高的) 那么右半部分就可以按照左半部分同理 只不过是从最右边开始往左走直到走到F

public int trap(int[] heights) {        if(heights.length < 2) return 0;        int result = 0;        int maxIndex = -1;        for(int temp = 0;temp < heights.length;temp++){            if(maxIndex == -1 || heights[temp] > heights[maxIndex])                maxIndex = temp;        }        int height = heights[0];        for(int i = 0;i < maxIndex;i++){            if(heights[i] > height) height = heights[i];            else result += height - heights[i];        }        height = heights[heights.length - 1];        for(int i = heights.length - 1;i > maxIndex;i--){            if(heights[i] > height) height = heights[i];            else result += height - heights[i];        }        return result;    }

我想起来大二的时候数据结构是做过这个题的
和畅哥哥在良乡的图书馆。。。当时我想了很久。。而且当年用的都是C语言。。。怀念。。。

问题的粒度。。。。虽然想的是山顶。。但是不要真的去求山顶。。。以每个横坐标为粒度啊。。。。

0 0
原创粉丝点击