领扣 LeetCode 42:接雨水(java)(网易有道面试真题)
生活随笔
收集整理的這篇文章主要介紹了
领扣 LeetCode 42:接雨水(java)(网易有道面试真题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:鏈接
給定?n?個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之后能接多少雨水。
上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。?感謝 Marcos?貢獻此圖。
示例:
輸入: [0,1,0,2,1,0,1,3,2,1,2,1] 輸出: 6解題思路:
第一步:遍歷整個數組,找到整個數組中最高的柱子,做好記錄
第二步:從左向右遍歷到那個最高柱子,找到并對左邊的最大值做好記錄,一旦有柱子比這個最大值低,那么這個位置可以裝水
第三步:從右向左遍歷到那個最高柱子,找到并對右邊的最大值做好記錄,一旦有柱子比這個最大值低,那么這個位置可以裝水
代碼:
class Solution {public int trap(int[] height) {int max = 0;int maxIndex = 0;for(int i =0 ;i< height.length; i++){if (max < height[i]){max = height[i];maxIndex = i;}}int sum = 0;int maxLeft = 0;int maxRight = 0;for (int a=0 ; a<maxIndex; a++){if (height[a]>=maxLeft){maxLeft = height[a];}else{sum+= maxLeft-height[a];}}for (int b=height.length-1 ; b>maxIndex; b--){if (height[b]>=maxRight){maxRight = height[b];}else{sum+= maxRight-height[b];}}System.out.print(sum);return sum;} }手動測試
public class Solution {public int trap(int[] height) {int max = 0;int maxIndex = 0;for(int i =0 ;i< height.length; i++){if (max < height[i]){max = height[i];maxIndex = i;}}int sum = 0;int maxLeft = 0;int maxRight = 0;for (int a=0 ; a<maxIndex; a++){if (height[a]>=maxLeft){maxLeft = height[a];}else{sum+= maxLeft-height[a];}}for (int b=height.length-1 ; b>maxIndex; b--){if (height[b]>=maxRight){maxRight = height[b];}else{sum+= maxRight-height[b];}}System.out.print(sum);//6return sum;}public static void main(String[] args){int[] height={0,1,0,2,1,0,1,3,2,1,2,1};Solution solution = new Solution();solution.trap(height);} }結果:
總結
以上是生活随笔為你收集整理的领扣 LeetCode 42:接雨水(java)(网易有道面试真题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode-595. 大的国家
- 下一篇: Leetcode-184. 部门工资最高