1. 程式人生 > >LeetCode Notes_#11 Container with Most Water

LeetCode Notes_#11 Container with Most Water

LeetCode Notes_#11 Container with Most Water

LeetCode 

Contents

題目

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.

container
container

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

思路和解答

思路

乍一看沒太好的思路,沒有一個固定的規律,還是要經過一些計算和比較的。那麼問題在於如何減少計算比較的次數呢?

解答

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        i,j=0
,len(height)-1#定義兩個指標去遍歷height陣列 res=0 while(i<j):#終止條件是兩個指標相等,相當於在中間相遇 res=max(res,min(height[i],height[j])*(j-i))#更新最大值 if height[i]>height[j]: j=j-1 else: i=i+1 return res

需要注意的點

  • 迴圈語句要用while,不要用for,因為迴圈的次數不是確定的,而是根據i,j的大小去決定
  • 每次迴圈只移動一個指標,並且移動的是高度較小那一側的指標,理由:
    • 首先不可能一次就同時移動兩邊的指標,會漏過一些可能的最大值
    • 其次如果移動高度較高的一側的指標,那麼也有可能錯過最大值