leetcode42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

思路:可以找到每个元素左边和右边最大的,当前bar可以装的大小即为min(max_left,max_right) - height[i]

前提是min(max_left,max_right) < height[i]

有两种方法,第一种比较粗暴,对每个元素分别找出左边最大,右边最大的时间复杂度O(n),空间复杂度O(n)

第二种,先找出所有元素中最大的,然后在两边分别分别处理,时间复杂度O(n),空间复杂度O(1)

AC1:


class Solution {
public:
    int trap(vector<int>& height) 
    {
        int result = 0;
        int size = height.size();
        if (size == 0)
            return result;
        if (size == 3)
            return (min(height[0],height[2]) - height[1]) > 0 ? (min(height[0],height[2]) - height[1]) : 0;
        
        vector<int> max_left;
        vector<int> max_right;
        int max = height[0];
        max_left.push_back(max);
        //计算每个元素左边最大的
        for (int i = 1; i < size - 2; i++)
        {
            max = max > height[i] ? max : height[i];
            max_left.push_back(max);
        }
        //计算每个元素右边最大的
        max_right.push_back(height[size - 1]);
        max = height[size - 1];
        for (int i = size - 2; i > 1; i--)
        {
            max = max > height[i] ? max : height[i];
            max_right.push_back(max);
        }
        //计算result
        for (int i = 0; i < size - 2; i++)
        {
            int temp = min(max_left[i],max_right[size - 3 - i]) - height[i + 1];
            if (temp > 0)
                result += temp;
        }
        
        return result;
    }
};



AC2:


class Solution {
public:
    int trap(vector<int>& height) 
    {
        int result = 0;
        int size = height.size();
        if (size < 3)
            return result;
        if (size == 3)
            return (min(height[0],height[2]) - height[1]) > 0 ? (min(height[0],height[2]) - height[1]) : 0;
        //找出最高的
        int max_index = 0;
        for (int i = 1; i < size; i++)
            if (height[i] > height[max_index])
                max_index = i;
        //搜索左边
        for (int i = 1,peak = 0; i < max_index; i++)
        {
            if (height[i] > height[peak])
                peak = i;
            else
                result += height[peak] - height[i];
        }
        //搜索右边
        for (int i = size - 2,peak = size - 1; i > max_index; i--)
        {
            if (height[i] > height[peak])
                peak = i;
            else
                result += height[peak] - height[i];
        }
        return result;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值