1. 程式人生 > 實用技巧 >leetcode刷題筆記--java實現

leetcode刷題筆記--java實現

42. 接雨水

本題目使用雙指標法進行求解,參考以下連線進行的演算法實現。

https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/327718

關鍵在於點出對於左側遍歷到的元素,其左側最大值left_max是確定的,但其右側最大值right_max是不確定的,因為其右側還有未被遍歷到的點可能比right_max更大。對於右側遍歷到的元素,其右側最大值right_max是確定的,但其左側最大值left_max是不確定的,因為其左側還有未被遍歷到的點可能比left_max更大。

故當left_max<right_max時,說明左側最大值必為兩個邊界中的較小值。此時對於第i處便可求得該列能存水的數量。

程式碼如下:

 1 public class Solution_Double_Pointer {
 2     public int trap(int[] height) {
 3         int left_max = 0;
 4         int right_max = 0;
 5         int left = 0;
 6         int right = height.length-1;
 7         int ans = 0;
 8         while (left<=right){
 9             if(left_max<right_max){
10 left_max = Math.max(left_max,height[left]); 11 ans+=Math.max(0,left_max-height[left]); 12 left++; 13 } 14 else { 15 right_max = Math.max(right_max,height[right]); 16 ans+=Math.max(0,right_max-height[right]);
17 right--; 18 } 19 } 20 return ans; 21 } 22 }

時間複雜度O(n),空間複雜度O(1)。