Leetcode 42 接雨水
Posted alf_cee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 42 接雨水相关的知识,希望对你有一定的参考价值。
动态规划方法:
class Solution public int trap(int[] height) int length = height.length; int[] leftLength = new int[length]; int[] rigthLength = new int[length]; int lefhMax = 0; int rigthMax = 0; //从左往右获取最高点 for (int i = 0; i < height.length; i++) lefhMax = Math.max(height[i], lefhMax); if (i == 0) leftLength[i] = 0; else int left = lefhMax - height[i]; if (left <=0 ) leftLength[i] = 0; else leftLength[i] = left; for (int i = height.length - 1; i >= 0; i--) rigthMax = Math.max(height[i], rigthMax); if(i == height.length - 1) rigthLength[i] = 0; else int right = rigthMax - height[i]; if (right <= 0) rigthLength[i] = 0; else rigthLength[i] = right; int vol = 0; for (int i = 0; i < height.length; i++) int iVol = Math.min(leftLength[i], rigthLength[i]); if (iVol > 0) // System.out.println("i=" + i + ", iVol=" + iVol); vol += iVol; else // System.out.println("i=" + i + ", iVol=" + 0); // System.out.println("vol =" + vol); return vol;
参考:leetcode 42. 接雨水(双指针、动态规划、单调栈)_The August的博客-CSDN博客
以上是关于Leetcode 42 接雨水的主要内容,如果未能解决你的问题,请参考以下文章