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.
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
思路
- 暴力遍歷碟嘴,依次遍歷容器的左右邊界,以左右邊界中高度較小的當(dāng)做容器高度,計(jì)算面積的诵。
# 1. 使用暴力搜索互订,時(shí)間復(fù)雜度為O(n**2)
def maxArea(self, height: List[int]) -> int:
max_area = 0
for i in range(0, len(height) - 1):
for j in range(i + 1, len(height)):
area = (j - i) * min(height[i], height[j])
max_area = max(area, max_area)
return max_area
- 雙指針?lè)ǎ?先以數(shù)組的最左最右當(dāng)做容器的左右邊界吧慢,再向中間收斂马靠。因?yàn)閺臄?shù)組兩端開(kāi)始已經(jīng)保證了容器的最寬寬度吼鳞,現(xiàn)在要找更高的高度看蚜,如果左邊界高度小于右邊界,則左邊界向里移動(dòng)赔桌,否則右邊界向內(nèi)移動(dòng)供炎。
# 2. 雙指針,向內(nèi)收斂疾党,時(shí)間復(fù)雜度為O(n)
def maxArea2(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
max_area = 0
while (l < r):
area = (r - l) * min(height[l], height[r])
max_area = max(max_area, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
return max_area