LeetCode ——42. 接雨水

  解题思路:

  储水量由最小的一边决定,我们可以先从左右两边同时遍历,得到最大值,然后分两种情况处理:

  1.只有一个最大值(假设位置为i):

    这样就从左向i遍历,不断更新左边的最大值,加上小于当前左边最大值的差值,得到当前的储水量。

         同理,从右到左遍历到i,更新result。

  2.有两个及以上最大值的情况(假设最左边和最右边位置为i,j):

    只要在1的基础上,加上从i到j中间的部分,每个点加上的值为max-length[x]。

  最后得到结果,代码和时间性能如下:

  

int trap(vector<int>& height) {
    if (height.size() < 2)
        return 0;

    int lmax=0, rmax=0;
    int lpos, rpos;
    int j = height.size() - 1;
    int i = 0;
    while (i<=j)
    {
        if (height[i] > lmax)
        {
            lmax = height[i];
            lpos = i;
        }
        if (height[j] > rmax)
        {
            rmax = height[j];
            rpos = j;
        }
        i++;
        j--;
    }
    if (lmax > rmax)
    {
        rmax = lmax;
        rpos = lpos;
    }
    else if (lmax < rmax)
    {
        lmax = rmax;
        lpos = rpos;
    }

    int count = 0, result = 0;
    int current = 0;
    for (int i = 0; i < lpos; i++)
    {
        if (height[i]>current)
            current = height[i];
        if (current - height[i] > 0)
            result += (current - height[i]);
    }
    for (int i = lpos; i <= rpos; i++)
        result += (rmax - height[i]);
    current = 0;
    for (int i = height.size() - 1; i > rpos; i--)
    {
        if (height[i]>current)
            current = height[i];
        if (current - height[i] > 0)
            result += (current - height[i]);
    }
    return result;
}

扫描二维码关注公众号,回复: 1839823 查看本文章

猜你喜欢

转载自www.cnblogs.com/Oscar67/p/9256211.html
今日推荐