標籤: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