Leetcode: trapping-rain-water
来源:互联网 发布:mac 建立文件夹 编辑:程序博客网 时间:2024/06/05 19:03
题目:
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!
思路:
1.遍历数组,找出最大值的下标;
2.分别从左右向中间遍历;
3.设置left=0,right=0;分别表示遍历过程中出现的最大值
4.若left>A[i](right>A[i]),说明当前是洼地,累加面积
代码:
public class Solution { public int trap(int[] A) { int max=0; int left=0; int right=0; for(int i=0; i<A.length; i++) { if(A[i] > A[max]) max = i; } int sum = 0; for(int i=0; i<max;i++) { if(A[i]>=left) left=A[i]; else sum+= left-A[i]; } for(int i=A.length-1; i>max;i--) { if(A[i]>=right) right=A[i]; else sum+= right-A[i]; } return sum; }}
1 0
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [LeetCode]Trapping Rain Water
- LeetCode-Trapping Rain Water
- [leetcode] Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- Leetcode:Trapping Rain Water
- [LeetCode] Trapping Rain Water
- <Leetcode>Trapping Rain Water
- Leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- leetcode Trapping Rain Water
- LeetCode Trapping Rain Water
- LeetCode | Trapping Rain Water
- qt 获取窗口句柄
- -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOME environment variable
- python正则之match search
- Java基础(一)
- idea创建多个maven项目java文件夹不是绿色
- Leetcode: trapping-rain-water
- Javascript之深入浅出prototype
- 二进制包安装tomcat-8.5 (centos-6.8)
- Arduino烧写bootloader
- ahk秘籍汇总
- 1032. Sharing (25)
- ahk 0.基本用法和语法
- ahk 1.基本命令
- MNF最小噪声分离变换(转)