zoukankan      html  css  js  c++  java
  • [LintCode] 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.

    Trapping Rain Water

     
    Example

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

    Challenge

    O(n) time and O(1) memory

    O(n) time and O(n) memory is also acceptable.

    class Solution {
    public:
        int trap(vector<int>& heights) {
            if(heights.size() < 3) return 0;
            int waterNum = 0, left = 0, right = heights.size() - 1, 
                leftH = heights[left], rightH = heights[right];
            
            while(left < right){
                if(leftH < rightH){
                    int t = left + 1;
                    if(t < right){
                        if(heights[t] < leftH)
                            waterNum += leftH - heights[t];
                        else leftH = heights[t];
                    }
                    left = t;
                }else{
                    int t = right - 1;
                    if(t > left){
                        if(heights[t] < rightH)
                            waterNum += rightH - heights[t];
                        else rightH = heights[t];
                    }
                    right = t;
                }
            }
            return waterNum;
        }
    };
  • 相关阅读:
    🔺 Garbage Remembering Exam UVA
    Cows and Cars UVA
    Probability|Given UVA
    Crossing Rivers HDU
    均匀分布和高斯分布
    Race to 1 UVA
    XMPPElementReceipt wait return,
    someone like you,
    第三方统计,
    截获的感觉,
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/4858562.html
Copyright © 2011-2022 走看看