当前位置:网站首页>【LeetCode】11、盛最多水的容器
【LeetCode】11、盛最多水的容器
2022-06-24 21:21:00 【小曲同学呀】
11、盛最多水的容器
题目:
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。

输入:[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 <= 10^5
0 <= height[i] <= 10^4
解题思路:
仔细看了下示例1的图,发现就是让找区域最大面积的。题目还说了一大堆废话。
总而言之就一句话:找寻最大的一组(i,j),使得Area最大;
这里需要用到动态规划和双指针,基本的表达式为:Area = Max(min(height[i], height[j]) * (j-i)) {其中0 <= i < j < height,size()};
- 使用两个指针,值小的指针向内移动,这样就减小了搜索空间
- 因为面积取决于指针的距离与值小的值乘积
- 如果值大的值向内移动,距离一定减小
- 而求面积的另外一个乘数一定小于等于值小的值,因此面积一定减小
- 而我们要求最大的面积,因此值大的指针不动,而值小的指针向内移动遍历
参考代码:
class Solution {
public int maxArea(int[] a) {
int max = 0;
for(int i = 0, j = a.length - 1; i < j ; ){
int minHeight = a[i] < a[j] ? a[i ++] : a[j --];
max = Math.max(max, (j - i + 1) * minHeight);
}
return max;
}
}

边栏推荐
- 期望与方差
- Abnova丨5-甲基胞嘧啶多克隆抗体中英文说明
- VB 学习笔记
- Bi-sql top
- Tencent cloud wecity solution
- Redis basic commands and types
- 梦想CAD云图与GIS结合演示
- Q1季度逆势增长的华为笔电,正引领PC进入“智慧办公”时代
- Install mysql5.6 under linux64bit - the root password cannot be modified
- Library management system code source code (php+css+js+mysql) complete code source code
猜你喜欢

Fan benefits, JVM manual (including PDF)

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

15.线程同步的几种方法

JVM指令

4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?

Bi-sql - join

4 ans d'expérience de travail, 5 modes de communication Multi - thread ne peuvent pas être décrits, vous osez croire?

修身励学篇

The innovation consortium of Haihe laboratory established gbase and became one of the first member units of the innovation Consortium (Xinchuang)

明日考试 最后一天如何备考?二造考点攻略全整理
随机推荐
4 ans d'expérience de travail, 5 modes de communication Multi - thread ne peuvent pas être décrits, vous osez croire?
“一个优秀程序员可抵五个普通程序员!”
[untitled]
The optimism about technology is making Dell achieve more than expected
Using macro code to generate handwriting automatically in word or WPS
Powerbi - for you who are learning
Assembly language (4) function transfer parameters
Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?
Yasea APK Download Image
搜索二维矩阵[二分巧用 + 记录不同于插入二分的解法]
mpls 笔记 part 1
Bi SQL drop & alter
Fan benefits, JVM manual (including PDF)
粉丝福利,JVM 手册(包含 PDF)
Redis and jedis
Matlab rounding
MySQL gets the primary key and table structure of the table
卷积与反卷积关系超详细说明及推导(反卷积又称转置卷积、分数步长卷积)
What to learn in VB [easy to understand]
天书夜读笔记——8.4 diskperf反汇编