【leetcode】盛最多水的容器【python】
阿新 • • 發佈:2018-12-14
題目連結 採用暴力解法回超時,時間複雜度為O(N^2) 採用雙指標的辦法,注意,比較低的那條邊決定著面積,因此,將比較低的那條邊往中間挪動就好了,直到相鄰之後輸出,而不是左邊移動一次,右邊移動一次,需要注意只有兩個數的情況,在python裡面,range(1,1)是沒有結果的
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ i, j = 0, len(height) - 1 MaxArea = (j - i) * (min(height[i], height[j])) while True: print(i, j) if height[i] <= height[j]: for m in range(i, j): if height[m] > height[i]: i = m break if m == j - 1: return MaxArea else: for n in range(j, i , -1): if height[n] > height[j]: j = n break if n == i + 1: return MaxArea Area = (j - i) * min(height[i], height[j]) if Area > MaxArea: MaxArea = Area height = [1,1] print(Solution().maxArea(height))