zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    并发工具类的使用 CountDownLatch,CyclicBarrier,Semaphore,Exchanger
    多线程按顺序执行3个方法
    读写锁事例
    使用AQS自定义重入锁
    java 几种锁实现
    Nginx 安装
    Windows 安装mysql
    day--14前端(HTML、CSS)
    day13--开发堡垒机
    day12--python操作mysql
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9256211.html
Copyright © 2011-2022 走看看