[ 熱題 HOT 100] ---42. 接雨水 ---雙指針《困難等級》

1 題目描述

在這裏插入圖片描述

2 解題思路

  • 方法:雙指針
    我們先明確幾個變量的意思:

left_max:左邊的最大值,它是從左往右遍歷找到的
right_max:右邊的最大值,它是從右往左遍歷找到的
left:從左往右處理的當前下標
right:從右往左處理的當前下標

在這裏插入圖片描述
自己的理解:

  • 第一層while循環體
    當left< right,符合條件的時候進入循環體

  • 第二層 if 條件判斷
    像下圖所示,如果左側高度<右側高度,積水量由左側決定,
    這時候右邊較大,那麼右邊就作爲右邊界,記錄左側的積水量,可以進入進入水量的循環體

左邊大的時候同理可得!
在這裏插入圖片描述

  • 第三層 if 嵌套操作
    當左邊的值小於右邊的值的時候,那麼
    對於左邊來說,
    如果現在所處位置的值> left_max,那麼更新left_max,
    否則,如果小於,那麼就形成凹陷,可以接到雨水,將差值加到res結果集中

對於右邊來說也是同理

3 解決代碼

  • 方法:雙指針《Java代碼》
class Solution {
    public int trap(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int left_max = 0;
        int right_max = 0;
        int res = 0;
        while(left < right){
            //如果左側高度<右側高度,積水量由左側決定,
            //這時候右邊較大,那麼右邊就作爲右邊界,記錄左側的積水量,可以進入進入水量的循環體
            if(height[left] < height[right]){
                if(height[left] >= left_max){
                    left_max = height[left];
                }
                else{
                    res += left_max- height[left] ;
                }
                left++;
            }
            else{
                if(height[right] >= right_max){
                    right_max = height[right];
                }
                else{
                    res += right_max - height[right];
                }
                right--;
            }
        }
        return res;

    }
}
  • 方法:雙指針《python3代碼》
class Solution:
    def trap(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        left_max = right_max = 0
        res = 0
        while left < right:
            if height[left] < height[right]:
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    res += left_max - height[left]
                left += 1
            else:
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    res += right_max - height[right]
                right -= 1

        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章