zoukankan      html  css  js  c++  java
  • 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!

    解决思路

    假设数组的长度为len,(1) 找到最高的那个柱子highest;

    (2) 双指针:从0到highest, 从len-1到highest;

    (3) 辅助栈s:存的是柱子高度的升序序列,如果遇到比栈顶元素小的高度,则能够储存水量为s.peek()-cur

    时间空间复杂度均为O(n).

    程序

    public class Solution {
        public int trap(int[] height) {
    		if (height == null || height.length == 0) {
    			return 0;
    		}
    		int highest = getHighestIdx(height);
    		int water = 0;
    		
    		Stack<Integer> s = new Stack<Integer>();
    		for (int i = 0; i < highest; i++) {
    			if (s.isEmpty() || height[i] > s.peek()) {
    				s.push(height[i]);
    			} else {
    				water += s.peek() - height[i];
    			}
    		}
    		
    		s = new Stack<Integer>();
    		for (int i = height.length - 1; i > highest; i--) {
    			if (s.isEmpty() || height[i] > s.peek()) {
    				s.push(height[i]);
    			} else {
    				water += s.peek() - height[i];
    			}
    		}
    		
    		return water;
    	}
    	
    	private int getHighestIdx(int[] height) {
    		int high = 0;
    		int idx = 0;
    		for (int i = 0; i < height.length; i++) {
    			if (height[i] > high) {
    				high = height[i];
    				idx = i;
    			}
    		}
    		return idx;
    	}
    }
    
  • 相关阅读:
    JSON2 源代码
    C#冒泡排序详解
    SqlHelper 带详细中文注释
    js-cookie
    淘宝镜像(cnpm) 安装
    vue全局刷新
    webpack-npm安装-查看当前版本
    半环进度条
    Parameter 'name' implicitly has an 'any' type.
    vue3.0-如何切换路由-路由模式ts
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4691359.html
Copyright © 2011-2022 走看看