已解决
LeetCode(28)盛最多水的容器【双指针】【中等】
来自网友在路上 11098109提问 提问时间:2023-11-19 06:41:04阅读次数: 109
最佳答案 问答题库1098位专家为你答疑解惑
目录
- 1.题目
- 2.答案
- 3.提交结果截图
链接: 盛最多水的容器
1.题目
给定一个长度为 n
的整数数组 height
。有 n
条垂线,第 i
条线的两个端点是 (i, 0)
和 (i, height[i])
。
找出其中的两条线,使得它们与 x
轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
**说明:**你不能倾斜容器。
示例 1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例 2:
输入:height = [1,1]
输出:1
提示:
n == height.length
2 <= n <= 105
0 <= height[i] <= 10^4
2.答案
class Solution {public int maxArea(int[] height) {int left = 0;int leftIndex = 0;int right = height.length - 1;int rightIndex = height.length - 1;while (left < right) {int oldArea = Math.min(height[leftIndex], height[rightIndex]) * (rightIndex - leftIndex);int newLeftArea = Math.min(height[left + 1], height[right]) * (right - (left + 1));int newRightArea = Math.min(height[left], height[right - 1]) * ((right - 1) - left);if (newLeftArea > oldArea) {leftIndex = ++left;rightIndex = right;continue;}if (newRightArea > oldArea) {leftIndex = left;rightIndex = --right;continue;}// 判断移动左指针还是右指针if (height[left] < height[right]) {left++;} else {right--;}}return Math.min(height[leftIndex], height[rightIndex]) * (rightIndex - leftIndex);}
}
3.提交结果截图
整理完毕,完结撒花~ 🌻
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"LeetCode(28)盛最多水的容器【双指针】【中等】":http://eshow365.cn/6-38995-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: <MySQL> 什么是JDBC?如何使用JDBC进行编程?
- 下一篇: 网络编程TCP/UDP通信