zoukankan      html  css  js  c++  java
  • leetcode 42 Trapping Rain Water ---java

    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!

    这道题看图很好理解,题目意思就不赘述了。

    第一次的想法是,先遍历最大的一个数,然后以此为分界点,前后分别求出面积,然后减去本身的高度,就是所求答案。

    package leetcode;
    
    public class trap {
    	public int trap(int[] height) {
    	  int len = height.length;
              if(len < 2)
                  return 0;
              int max = 0, pos = 0;
              for( int i = 0; i<len ; i++){
            	if(max < height[i]){
            		max = height[i];
            		pos = i;
            	}
              }
              int b_pos = 0,a_pos = len-1;
              int all = 0;
              for( int i = 0; i<=pos ; i++){
              	if( height[i]>=height[b_pos] ){
            		all+=height[b_pos]*(i - b_pos);
            		b_pos = i;
            	}
            	all-=height[i];
              }
              for( int i = len-1;i>=pos;i--){
              	if( height[i]>=height[a_pos] ){
            		all+=height[a_pos]*(a_pos - i);
            		a_pos = i;
            	}
            	all-=height[i];
              }
           
              return all+height[pos];
        }
    }
    

     但是结果并没有达到最优,总体思想有一些微变,就达到了最佳。时间复杂度o(n)。空间复杂度1。

    package leetcode;
    
    public class trap {
    	public int trap(int[] height) {
    		int len = height.length;
    		if (len < 2)
    			return 0;
    		int be = 0, af = len - 1, result = 0;
    		int po1 = 0, po2 = len - 1;
    		while (be < af) {
    			if (height[po1] <= height[af]) {
    				while (be < af && height[be] <= height[po1]) {
    					result -= height[be];
    					be++;
    				}
    				result += height[po1] * (be - po1);
    				po1 = be;
    			} else {
    				while (af > be && height[af] <= height[po2]) {
    					result -= height[af];
    					af--;
    				}
    				result += height[po2] * (po2 - af);
    				po2 = af;
    			}
    		}
    		return result;
    
    	}
    }
    
  • 相关阅读:
    centos7之防止root密码被破解
    近期codeforces做题的总结?(不定期更新)
    小程序分享微信好友
    小程序自定义头部导航栏滑动颜色渐变
    小白快速上手的react.js教程
    架构型设计模式-同步模式
    仿vue-cli写一个简易的脚手架
    VUE基础知识篇-vue从零开始学VUE
    彻底理解Vue组件间7种方式通信
    设计模式--观察者模式
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5604094.html
Copyright © 2011-2022 走看看