码迷,mamicode.com
首页 > 移动开发 > 详细

42. Trapping Rain Water

时间:2020-01-21 00:39:20      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:code   its   text   rap   rip   class   res   math   element   

/**
 * 42. Trapping Rain Water
 * https://leetcode.com/problems/trapping-rain-water/description/
 * */
class Solution {
    fun trap(height: IntArray): Int {
        /*
        * 当前点的水量等于他左边的最高值与右边的最高值的差-当前点的量
        * val n = height.size
        * iVal = min(max(height[0,i]), max(height[i,n-1])) - height[i]
        *
        * time complexity O(n*n)
        * space complexity O(1)
        *
        * 还可以优化!
        * */
        var result = 0
        val n = height.size
        for (i in 0 until n) {
            var left = height[i]
            //find the maximum element in its left
            for (l in 0 until i) {
                left = Math.max(left, height[l])
            }
            var right = height[i]
            //find the maximum element in its right
            for (r in i until n) {
                right = Math.max(right, height[r])
            }
            result += Math.min(left, right) - height[i]
        }
        return result
    }
}

42. Trapping Rain Water

标签:code   its   text   rap   rip   class   res   math   element   

原文地址:https://www.cnblogs.com/johnnyzhao/p/12219874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!