Leetcode第十一題:盛最多水的容器

題目:

給你 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

說明:你不能傾斜容器,且 n 的值至少爲 2。

 

圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示爲藍色部分)的最大值爲 49。

示例:

輸入:[1,8,6,2,5,4,8,3,7]
輸出:49

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/container-with-most-water
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

個人思路:

我用我聰明的小腦袋瓜想出了遍歷這個好方法,indexDistance *  minInTwoNums

官方答案推薦:

雙指針法:適用於邊界問題,即頭尾指針,中間範圍內所有元素都可以作爲新的邊界。頭尾各一個指針,每次計算後移動數字較小的那一個(因爲indexDistance要減一,那肯定選擇移動數字小的)。

python代碼:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        startIndex = 0
        endIndex = len(height) - 1
        maxWater = 0
        curWater = 0
        while startIndex != endIndex:
            curWater = (endIndex - startIndex) * min(height[startIndex],height[endIndex])
            maxWater = curWater if curWater>maxWater else maxWater
            if height[startIndex] < height[endIndex]:
                startIndex += 1
            else:
                endIndex -= 1
        
        return maxWater

反思:

我也只能想到遍歷這種聰明的方法了。時間複雜度n^2和n^1也就差了1而已,不虧。

當一個無情的看答案寫代碼機器。

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