LeetCode-Trapping Rain Water-下雨積水-單調隊列應用

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   for   sp   div   

https://oj.leetcode.com/problems/trapping-rain-water/

這道題使用單調隊列能夠O(n)時間解決。維護一個降序排列的單調隊列。如果Ai>A[que.front]就說明能夠使用que.front作為頂部計算一次積水。

當從0-n時,須注意隊列中還有元素。需要反向再執行一次單調隊列。但是只需要到之前隊列的front的位置即可。

class Solution {public:    int trap(int A[], int n) {        if (n==0) return 0;        queue <int> que;        que.push(0);        int res=0;        for (int i=1;i<n;i++){            int cur=A[i];            int t=A[que.front()];            if (cur<t) que.push(i);            else{                while(!que.empty()){                    res+=t-A[que.front()];                    que.pop();                }                que.push(i);            }        }        if (que.empty()) return res;        int m=que.front();        while(!que.empty()) que.pop();        que.push(n-1);        for (int i=n-2;i>=m;i--){            int cur=A[i];            int t=A[que.front()];            if (cur<t) que.push(i);            else{                while(!que.empty()){                    res+=t-A[que.front()];                    que.pop();                }                que.push(i);            }        }        return res;    }};

 

LeetCode-Trapping Rain Water-下雨積水-單調隊列應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.