题目:https://leetcode-cn.com/problems/container-with-most-water/

根据题目的要求,我们可以得知:
- 需要求的是一个矩形的面积,而不是其它形状的面积。
- 这个矩形的面积是由高度较低的点来决定。
方法一:暴力解题
最容易想到的方法就是将所有点进行两两组合,得出所有组合的面积,然后取最大的面积即可。但这种方法的时间复杂度为。
function maxArea(height: number[]): number {let max = 0;for (let i = 0; i < height.length; i++) {for (let j = i + 1; j < height.length; j++) {let tmp = (j - i) * Math.min(height[i], height[j])if (tmp > max) {max = tmp}}}return max};
上面循环中,第二个 for 循环 let j = i + 1 这个可以减少重复遍历,举一下例子来说明一下:
1 2 31 x2 x x3 x x x
假设非负数分别为 1,2,3。那么这三个数两两组合就有 1,2;1,3;2,3。我们假设横轴是 i,而纵轴是 j,表中 x 的地方为重复的组合,我们可以看出不重复的地方,i 和 j 的关系始终为 j = i + 1。
- 时间复杂度:
- 空间复杂度:
方法二:双指针法
leetcode 官网已经有非常好的双指针法解释,这里不再赘述,下面给出 TypeScript 的解法。
function maxArea(height: number[]): number {let leftIndex = 0let rightIndex = height.length - 1let maxArea = 0while (leftIndex < rightIndex) {const area = Math.min(height[leftIndex], height[rightIndex]) * (rightIndex - leftIndex)maxArea = Math.max(area, maxArea)height[leftIndex] > height[rightIndex] ? rightIndex-- : leftIndex++}return maxArea}
- 时间复杂度:
- 空间复杂度:
