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


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

思路:矩形面積最大,比較簡單

 

 

方案一:兩個循環,很容易實現,耗時有點長

class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_area = 0
        temp_area = 0
        length = 0
        max_length = len(height)
        if max_length < 2:
            return 0
        for i in range(max_length):
            for j in range(max_length):
                if height[i] <= height[j] :
                    short_height = height[i]
                    high_height = height[j]
                    length = abs(j - i)
                    temp_area = short_height * length
                else:
                    short_height = height[j]
                    high_height = height[i]
                    length = abs(i - j)
                    temp_area = short_height * length
                if temp_area >= max_area:
                    temp = temp_area
                    temp_area = max_area
                    max_area = temp
        return max_area
方案二:
class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_area = 0
        temp_area = 0
        index1 = 0
        index2 = len(height) - 1
        while index1 < index2:
            if height[index1] <= height[index2]:
                short_height = height[index1]
                high_height = height[index2]
                length = index2 - index1
                temp_area = short_height * length
                index1 += 1
            else:
                short_height = height[index2]
                high_height = height[index1]
                length = index2 - index1
                temp_area = short_height * length
                index2 -= 1
            if temp_area >= max_area:
                temp = temp_area
                temp_area = max_area
                max_area = temp
        return max_area 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM