给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
示例 2:
输入:height = [1,1]
输出:1
示例 3:
输入:height = [4,3,2,1,4]
输出:16
示例 4:
输入:height = [1,2,1]
输出:2
提示:
n = height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104
题意:其实就是求两个柱子之间的最大面积。
思路:从两边分别向里面遍历,哪边的柱子矮就移动这一侧的柱子向内移动,这样就可以保证移动后的面积会大于等于当前的面积。
详细题解:官方题解
正确代码:
class Solution {
public int maxArea(int[] height) {
int l=0,r= height.length-1;
int ans=0;
while(l<r){
int maxx=(r-l)*Math.min(height[l],height[r]);
ans =Math.max(maxx,ans);
if(height[l]<= height[r]){
l++;
}else {
r--;
}
}
return ans;
}
}
完整代码(含测试样例):
package com.Keafmd.April.day13;
/**
* Keafmd
*
* @ClassName: ContainerWithMostWater
* @Description: 盛最多水的容器 https://leetcode-cn.com/problems/container-with-most-water/
* @author: 牛哄哄的柯南
* @Date: 2021-04-13 9:30
* @Blog: https://keafmd.blog.csdn.net/
*/
public class ContainerWithMostWater {
public static void main(String[] args) {
Solution0413 solution0413= new Solution0413();
int [] height = {1,3,2,5,25,24,5};
int re = solution0413.maxArea(height);
System.out.println("re = " + re);
}
}
class Solution0413 {
public int maxArea(int[] height) {
int l=0,r= height.length-1;
int ans=0;
while(l<r){
int maxx=(r-l)*Math.min(height[l],height[r]);
ans =Math.max(maxx,ans);
if(height[l]<= height[r]){
l++;
}else {
r--;
}
}
return ans;
}
}
输出结果:
re = 24
Process finished with exit code 0
看完如果对你有帮助,感谢点赞支持!
如果你是电脑端,看到右下角的 “一键三连” 了吗,没错点它[哈哈]
加油!
共同努力!
Keafmd
一. 前言 前面两篇文章给大家介绍了使用gRPC的入门以及双向流的使用,今天介绍的...
题目链接 https://ac.nowcoder.com/acm/contest/12548/I 分析 直线用 y kx b 来...
DynamoDB 是 Amazon 基于《 Dynamo: Amazons Highly Available Key-value Store ...
目录 产品简述 应用环境 电路设计 产品简述 SX1268是Semtech公司推出的一款远距...
深入学习MySQL从概览MySQL逻辑架构开始。 首先来看一下MySQL的逻辑架构图 MySQL...
0x00 前言 在某些环境下,访问Web服务器的资源需要通过NTLM Over HTTP协议进行NT...
IT之家12月30日消息外媒 Windows Latest 报道,为了帮助你更快地找到应用程序,...
本文主要是总结了工作中一些常用的操作,以及不合理的操作,在对慢查询进行优化...
多线程与爬虫 目标url json中查找url 访问url 读取json 查看json的list数组 全部...
编外话 如果你对html一无所知,还苦恼与html如何入门,笔者很建议你学习下这篇文...