Description
Difficulty: Medium
Given
n
non-negative integersa1, a2, ..., an
, where each represents a point at coordinate(i, ai)
.n
vertical lines are drawn such that the two endpoints of the linei
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.
Example 1:
1
2
3 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:
1
2 Input: height = [1,1]
Output: 1Example 3:
1
2 Input: height = [4,3,2,1,4]
Output: 16Example 4:
1
2 Input: height = [1,2,1]
Output: 2Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
容器的体积等于底×高,底等于x轴的长度,高是两边柱子中短的一根的长度,因此这道题可以用双指针从最左最右开始一点点往中间走寻找最高值。
示例:
1 | [1,8,6,2,5,4,8,3,7] |
Code:
1 | class Solution { |
Summary
- pointer, pointer, pointer!
总之希望自己能坚持下去,每周记录分享几道有趣的题和解法。也欢迎大家留言讨论补充(●’◡’●)