1、原题
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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
![](https://img.haomeiwen.com/i2972377/b04fac089b38d265.jpg)
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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 2:
Input: height = [1,1]
Output: 1
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
2、思路
3、代码
class Solution {
func maxArea(_ height: [Int]) -> Int {
// 定义最大面积
var max = 0
// 使用首尾逼近的方法
var i = 0
var j = height.count - 1
// 定义需要的最小高度
var minHeight = 0
// 循环逼近
while i < j {
// 得出每次的最小高度
if height[i] < height[j] {
minHeight = height[i]
// 左边的高度最小,就将左边的边界右移一位
i+=1
} else {
minHeight = height[j]
// 右边的高度最小,就将右边的边界左移一位
j-=1
}
// 计算面积,因为最小的高度才是决定面积的
let area = (j - i + 1) * minHeight
// 比较得出最大面积
max = max > area ? max : area
}
return max
}
}
网友评论