• 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;
    	}
    }
    
  • 相关阅读:
    Delphi 获取不重复随机数《LceMeaning》
    轻松一下
    MS SQL字段类型详解《转》
    Go语言优势与劣势
    go语言特点
    初始go语言
    django 短链接改成长连接
    extjs [1]
    Supervisor安装与配置
    InfluxDB命令使用
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4691359.html
Copyright © 2020-2023  润新知