LeetCode 42. Trapping Rain Water

來源:互聯網
上載者:User

標籤:int   leetcode   solution   左右   自己   元素   turn   檢查   div   

 

 

https://leetcode.com/articles/trapping-rain-water/

做完了一道hard難度的題目,個人還是很激動的,突然那覺得“雙指標”簡直就是神器,題目要求整個容器能盛下的水的數量,直觀上來看,只有凹槽部分才能盛水,暴力搜尋法複雜度太高,最佳方法是使用雙指標,左右各放置一個,注意到盛水的多少是較短的那一邊決定,如果左邊高度小於右邊,那麼繼續檢查左邊高度是否大於等於left_max,如果是更新left_max,否則累加存水量;右邊情況類似,

代碼如下

 1 class Solution { 2 public: 3     int trap(vector<int>& height) { 4         //自己根據官方答案虛擬碼完成 5         int len = height.size(); 6         int left = 0, right = len - 1; 7         //int ans = 0, left_max = height[left], right_max = height[right]; 8         int ans = 0, left_max = 0, right_max = 0;  //這裡mgax都要初始化為0,否則會出錯,比如height為空白,上面的代碼會訪問下標為-1的元素 9         while (left < right)10         {11             if (height[left] < height[right])12             {13                 if (height[left] >= left_max)14                     left_max = height[left];15                 else16                     ans += left_max - height[left];17                 left++;18             }19             else20             {21                 if (height[right] >= right_max)22                     right_max = height[right];23                 else24                     ans += right_max - height[right];25                 right--;26             }27         }28         return ans;29     }30 };

時間複雜度:O(n)

空間複雜度:O(1)

 

二刷,2018-03-14,漏掉更新righ與left的部分了

LeetCode 42. 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.