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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM