leetcode解题方案--042--Trapping Rain Water
2017-11-23 20:52
531 查看
题目
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.
类似题目,格板储水和美团直方图(栈)
对于每一个格子来说,其左侧的最高板和右侧的最高板决定了水的高度。
所以结合动态规划,分别遍历两次。得到的两个数组分别表示,这个格儿的左侧最高板和右侧最高板儿。
两个值取小,得到答案。
public static int trap(int[] height) { if (height.length<=2) { return 0; } int[] leftMax = new int[height.length]; int[] rightMax = new int[height.length]; leftMax[0] = height[0]; rightMax[height.length-1] = height[height.length-1]; for (int i = 1; i < height.length-1; i++) { leftMax[i] = Math.max(leftMax[i-1], height[i]); rightMax[height.length-i-1] = Math.max(rightMax[height.length-i], height[height.length-i-1]); } // System.out.print(Arrays.toString(leftMax)); // System.out.print(Arrays.toString(rightMax)); int container = 0; for (int i = 1; i<height.length-1; i++) { int max = Math.min(leftMax[i], rightMax[i]); container = container+(max-height[i]); } return container; }
不知道为什么代码的字体和发布后的博客代码字体总是不一样,有知道的大佬麻烦留个言。
相关文章推荐
- leetcode 042 —— Trapping Rain Water
- LeetCode042 Trapping Rain Water
- LeetCode解题报告—— Trapping Rain Water
- leetcode解题笔记-Trapping Rain Water
- [LeetCode]042-Trapping Rain Water
- [LeetCode] Trapping Rain Water 解题报告
- leetcode解题方案--073--set matrix zeroes
- leetcode解题方案--167--Two Sum II - Input array is sorted
- leetcode;Trapping Rain Water
- LeetCode 42 Trapping Rain Water
- leetcode - Trapping Rain Water
- leetcode Trapping Rain Water
- leetCode_Trapping Rain Water
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- leetcode解题方案--012--Integer to Roman
- LeetCode(42)--Trapping Rain Water
- leetcode -- Trapping Rain Water
- leetcode解题方案--046--Permutations
- Leetcode 42 Trapping Rain Water
- leetcode解题方案--013--Roman to Integer