LeetCode 42 Trapping Rain Water(積水體積)

來源:互聯網
上載者:User

標籤:div   href   desc   ret   return   log   ==   odi   mil   

題目連結: https://leetcode.com/problems/trapping-rain-water/?tab=Description  Problem: 根據所給數組的值,按照的。求解積水最大體積。  首先對所給數組進行遍曆操作,求出最大高度所對應的下標為maxIndex 之後從左向右進行遍曆,設定左邊高度為leftMax 並初始化為 height[0],從i==1到i==maxIndex進行遍曆。不斷更新water,以及leftMax    當height[I]小於leftMax時,water += leftMax - height    當height[i]大於leftMax時,leftMax = height[I] 之後從i==height.length - 2到下標 I == maxIndex進行遍曆操作 初始化rightMax = height[height.length-1]    當height[I]小於rightMax時,water+=rightMax - height[I]    當height[I]大於rightMax時,rightMax = height[I]
 函數結果返回water 參考代碼: 
package leetcode_50;/*** *  * @author pengfei_zheng * 求積水的體積 */public class Solution42 {    public static int trap(int[] height) {        if (height.length <= 2) return 0;        int max = -1;        int maxIndex = 0;        for (int i = 0; i < height.length; i++) {            if (height[i] > max) {                max = height[i];                maxIndex = i;            }        }                int leftMax = height[0];        int water = 0;        for (int i = 1; i < maxIndex; i++) {            if (height[i] > leftMax) {                leftMax = height[i];            } else {                water += leftMax - height[i];            }        }                int rightMax = height[height.length - 1];        for (int i= height.length - 2; i > maxIndex; i--) {            if (height[i] > rightMax) {                rightMax = height[i];            } else {                water += rightMax - height[i];            }        }                return water;    }    public static void main(String[]args){//        int []height={0,1,0,2,1,0,1,3,2,1,2,1};        int []height={10,0,11,0,10};        System.out.println(trap(height));    }}

 

LeetCode 42 Trapping Rain Water(積水體積)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.