[LeetCode]Trapping Rain Water,解题报告
2014-01-02 11:11
435 查看
前言
在LeetCode上又碰到了一道笔试原题,充分说明提前的准备对应届生找工作有多大的作用,年终总结我会具体写一下自己找工作的准备历程,耗时将近半年时间题目
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.
解题思路
首先,碰到这样的题目不要慌张,挨个分析每个A[i]能trapped water的容量,然后将所有的A[i]的trapped water容量相加即可其次,对于每个A[i]能trapped water的容量,取决于A[i]左右两边的高度(可延展)较小值与A[i]的差值,即volume[i] = [min(left[i], right[i]) - A[i]] * 1,这里的1是宽度,如果the width of each bar is 2,那就要乘以2了
AC代码
public class Solution { public int trap(int[] A) { // special case if (A == null || A.length == 0) { return 0; } int i, max, volume, left[] = new int[A.length], right[] = new int[A.length]; // from left to right for (left[0] = A[0], i = 1, max = A[0]; i < A.length; i++) { if (A[i] < max) { left[i] = max; } else { left[i] = A[i]; max = A[i]; } } // from right to left for (right[A.length - 1] = A[A.length - 1], i = A.length - 2, max = A[A.length - 1]; i >= 0; i--) { if (A[i] < max) { right[i] = max; } else { right[i] = A[i]; max = A[i]; } } // trapped water for (volume = 0, i = 1; i <= A.length - 2; i++) { int tmp = Math.min(left[i], right[i]) - A[i]; if (tmp > 0) { volume += tmp; } } return volume; } }
相关文章推荐
- [leetcode] 407. Trapping Rain Water II 解题报告
- Leetcode 407. Trapping Rain Water II 收集雨水2 解题报告
- [LeetCode] Trapping Rain Water 解题报告
- 【LeetCode】Trapping Rain Water解题报告
- [LeetCode] Trapping Rain Water 解题报告
- LeetCode: Trapping Rain Water 解题报告
- [Leetcode] 407. Trapping Rain Water II 解题报告
- 【LeetCode】42.Trapping Rain Water(Hard)解题报告
- LeetCode 42: Trapping Rain Water 解题与思考
- [leetcode] 42. Trapping Rain Water 解题报告
- [Leetcode] 42. Trapping Rain Water 解题报告
- [LeetCode] Trapping Rain Water
- [leetcode] Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [LeetCode] [Trapping Rain Water 2012-03-10]
- LeetCode42——Trapping Rain Water
- LeetCode_Trapping Rain Water
- 【Leetcode】Trapping Rain Water
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
- [LeetCode] Trapping Rain Water 搜集雨水