LeetCode_Everyday:011 Container With Most Water

LeetCode_Everyday:011 Container With Most Water


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

給你 n 個非負整數 a1,a2,..,ana_1,a_2, .., a_n,每個數代表座標中的一個點 (i,ai)(i, a_i) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i,ai)(i, a_i)(i,0)(i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少爲 2。

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

示例:

示例 1:

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

代碼

方法一: 雙指針法 題注

執行用時 :72 ms, 在所有 Python3 提交中擊敗了59.70%的用戶
內存消耗 :15.2 MB, 在所有 Python3 提交中擊敗了6.90%的用戶

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        i, j, res = 0, len(height) - 1, 0
        while i < j:
            if height[i] < height[j]:
                res = max(res, height[i] * (j - i))
                i += 1
            else:
                res = max(res, height[j] * (j - i))
                j -= 1
        return res
    
"""
For Example:    input:   height = [1,8,6,2,5,4,8,3,7]
               output:   49
"""
height = [1,8,6,2,5,4,8,3,7]
                
solution = Solution()
result = solution.maxArea(height)
print('輸出爲:', result)   # 49

參考

  1. https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

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