Java实现-接雨水

来源:互联网 发布:广电总局下架网络剧 编辑:程序博客网 时间:2024/06/11 19:49

public class Solution {    /**     * @param heights: an array of integers     * @return: a integer     */    public int trapRainWater(int[] heights) {        // write your code here        int left = 0, right = heights.length - 1;         int res = 0;        if(left >= right)            return res;        int leftheight = heights[left];        int rightheight = heights[right];        while(left < right) {            if(leftheight < rightheight) {                left ++;                if(leftheight > heights[left]) {                    res += (leftheight - heights[left]);                } else {                    leftheight = heights[left];                }            } else {                right --;                if(rightheight > heights[right]) {                    res += (rightheight - heights[right]);                } else {                    rightheight = heights[right];                }            }        }        return res;    }}