当前位置:网站首页>成水最多的容器
成水最多的容器
2022-06-26 06:12:00 【Oh No 发量又少了】
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 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
示例 3:
输入:height = [4,3,2,1,4]
输出:16
示例 4:
输入:height = [1,2,1]
输出:2
方法一(此方法我在测试的时候由于超出时间而未通过)
public class Solution {
public int maxArea(int[] height) {
int max = 0;
for (int i = 0; i < height.length - 1; ++i) {
for (int j = i + 1; j < height.length; ++j) {
int area = (j - i)*Math.min(height[i],height[j]);
max = Math.max(area,max);
}
}
return max;
}
}
方法二(注意i++是先赋值后运算)
public 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--];
int area = (j - i+1)*minHeight;//由于i++和i--都是先赋值后运算,所以在此处要多加一个1才能运算准确
max = Math.max(max,area);
}
return max;
}
}
方法三
class Solution {
public int maxArea(int[] a) {
int i = 0,j= a.length - 1,res = 0;
while (i < j) {
res = a[i] < a[j] ?
Math.max(res,(j - i)*a[i++])://i++和i--都是先赋值后运算,此时还是i
Math.max(res,(j - i)*a[i--]);
}
return res;
}
}
边栏推荐
- MySQL 索引底层原理
- Implement the runnable interface
- Logstash——Logstash向Email发送告警邮件
- PyTorch混合精度原理及如何开启该方法
- Spark source code analysis (I): RDD collection data - partition data allocation
- 100 cases of go language
- MySQL-09
- 01 golang and matlab code of knapsack problem
- A tragedy triggered by "yyyy MM DD" and vigilance before New Year's Day~
- Household accounting procedures (First Edition)
猜你喜欢

Understanding of nil in go language

Message queue - message transaction management comparison

Basic construction of SSM framework

Easy to understand from the IDE, and then talk about the applet IDE

PyTorch使用多GPU并行训练及其原理和注意事项

Keepalived to achieve high service availability

Typora activation method

Logstash -- send an alert message to the nail using the throttle filter

Library management system

Solve the problem that Cmdr cannot use find command under win10
随机推荐
Laravel 实现 groupBy 查询分组数量
302. 包含全部黑色像素的最小矩形 BFS
canal部署、原理和使用介绍
Household accounting procedures (First Edition)
跨域的五种解决方案
MySQL 索引底层原理
DS18B20详解
Definition of Halcon hand eye calibration
Typora activation method
低代码实时数仓构建系统的设计与实践
Implementation of third-party wechat authorized login for applet
numpy.log
100 cases of go language
MEF framework learning record
Prometheus和Zabbix的对比
[spark] how to implement spark SQL field blood relationship
Logstash——Logstash将数据推送至Redis
Logstash——使用throttle过滤器向钉钉发送预警消息
SSH keygen specifies the path
Record how to modify the control across threads