本文主要是介绍leetcode-42. Trapping Rain Water,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
leetcode-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.
基本上就是两点法,i和j分别从两端开始向中心移动。同事维护一个i和j之外最高的容器高度h就行,凡是低于h的i和j的值说明都有水。
public class Solution {public int trap(int[] height) {if(height==null || height.length <1) return 0;int i = 0, j = height.length-1,ret = 0,h=Math.min(height[i],height[j]);while(i<j){ret += h>height[i]? h-height[i] : 0;ret += h>height[j]? h-height[j] : 0;h = Math.max(h,Math.min(height[i],height[j]));if(height[i]<height[j])i++;elsej--;}return ret;}
}
这篇关于leetcode-42. Trapping Rain Water的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!