LeetCode 11. Container With Most Water

題目要求:

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.


分析:
1.暴力求解:
      在每一種匹配情況下進行比較,留下最大的"乘積"
   algorithm:
     pre: a list of int -- height
     psot: the max area
    
     area <- 0
     for i <- 0 to height.size():
 for j <- i+1 to height.size() :
           h <- min(height[i], height[j])
           if (j-i)*h > area :
       area = (j-i)*h
     return area
  時間複雜度: O(N^2)
2.
  從底最大開始,當底不斷減小,避免面積一定減小的情況。
 
  底的長度爲   匹配個數
    size          1
    size-1        2
    size-2        3
    ...          ...
    2            size-1
 
  我們是隻要求出最大面積,而不必要對所有的都進行求解,在當前情況下,只需向一定不是面積減小的方向變化即可。
簡單的情況
  長度爲size的時候:
    變爲長度爲size-1的情況,有且只有兩種方式:[0,size-2]和[1,size-1]
  面積求法爲: d*h ; 其中h爲height[0], height[size-1]中的最小值。
    不妨設height[0]是最小值,則[0,size-2]的面積一定是變小的(這裏不再解釋)所以下一情況中只需查看[1,size-1]的情況。
    以height[0]爲左邊界的任何長度不大於size的匹配面積都小於當前area:這裏的比較排除了n-2種情況。[0:1]\[0:2]\……\[0:size-2]
更爲一般的情況:
  現假定計算的 範圍爲[i:j] 且有i<j
      當對範圍進行進一步縮小時:
   if height[i] < height[j]
      i+= 1
          else
             j += 1
      排除的其它比較情況數爲 j-i-1 種
 [i:i+1]\……\[i:j-1]
算法:
    i <- 0 , j <- size-1
    area <- 0
    while i < j :
 h <- min(height[i],height[j])
 if (j-i)*h > area
    area <- (j-i)*h
 
 //範圍更新       
        if height[i] <= h
     i += 1
        else
     j -= 1     
代碼:
def maxArea(height ):
    '''
    height : list[int]
    return type: int
    '''
    ans = 0
    
    i = 0
    j = len(height)-1
    while i < j :
        h = min( height[i] , height[j] )
        new_area = (j-i)*h
        if new_area > ans :
            ans = new_area

        if height[i] == h :
            i += 1
        if height[j] == h :
            j -= 1
    return ans 

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