1. 程式人生 > >Container With Most Water

Container With Most Water

lis ati 復雜度 poi ner 遍歷 嵌套循環 超時 16px

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

分析:

方法一:使用最簡單的嵌套循環遍歷,找出每一種組合。但此方法超時

方法二:容器的盛水量取決於兩塊板中的最短板,所以兩個指針,一頭一尾,記錄其盛水量,然後向中間移動其較短的板,期間記錄最大盛水量,直至兩個指針相遇。這樣時間復雜度就由方法一的O(N2)變為了O(N)。使用兩個指針,一頭一尾的方法很值得借鑒。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        
""" n = len(height) i = 0 j = n-1 max_area = 0 while(i<j): if height[i] < height[j]: area = (j-i)*height[i] i += 1 else: area = (j-i)*height[j] j -= 1 if area > max_area: max_area
= area return max_area

Container With Most Water