• 42. 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!

    思路分析:从左至右,针对当前的高度,往右寻找,如果有大于等于当前高度的元素,则说明水平线应该拉到这儿,否则,应该找到在后面元素中相对最大的元素(如果有很多,则应该返回第一个元素)。cur指向这个返回的元素。

    class Solution {
    public:
        int next(vector<int>& height, int pos){//若果pos位置后面有大于等于height[pos]直接返回第一个这样的值的位置,否则,返回后续中(最大的高度并且是第一次出现)的下标位置
            if (pos >= height.size() - 1)//遍历到最后一个元素时,就应该结束了,因为蓄不了水
                return -1;
            int val = height[pos];
            int start = height[pos + 1];
            int res = pos + 1;
            for (int i = pos + 1; i<height.size(); i++)
            {
                if (height[i] >= val){//情况之一,后面元素存在大于等于当前元素高度的值
                    return i;
                }
                else if (height[i]>start){//情况之二,记录后面元素中相对最大的元素,并且是第一次出现的元素
                    res = i;
                    start = height[i];
                }
            }
            return res;
        }
        int trap(vector<int>& height) {
            if(height.size()==0)
                return 0;
            int result = 0;
            int start = 0;
            while (height[start] == 0){
                start++;
            }
            while (start<height.size()-1){
                int cur = next(height, start);
                int altitude = height[start]<height[cur] ? height[start] : height[cur];
                for (int i = start + 1; i<cur; i++){
                    result += (altitude - height[i]);
                }
                start = cur;
            }
            return result;
        }
    };
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    Android 内存分析工具 MAT(Memory Analyzer Tool)
    google教程
    webView中支持input的file的选择和alert弹出
    记录一些容易忘记的属性 -- UIImageView
    记录一些容易忘记的属性 -- UIGestureRecognize手势
    使用苹果提供的汉字转拼音方法
    关于Xcode调试的帖子,感觉不错,转来看看
    记录一些容易忘记的属性 -- UIKeyboard
    记录一些容易忘记的属性 -- NSTimer
    记录一些容易忘记的属性 -- UIView
  • 原文地址:https://www.cnblogs.com/chess/p/5307157.html
Copyright © 2020-2023  润新知