当前位置:网站首页>盛水最多的容器
盛水最多的容器
2022-08-08 06:26:00 【写做四月一日的四月一日】
题目来源:力扣11.盛水最多的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
方法一:使用双重for循环
外层循环控制左侧高度,内层循环控制右侧高度。
class Solution {
public int maxArea(int[] height) {
int maxCap = 0;
for(int i = 0; i < height.length - 1; i++){
for(int j = height.length - 1; j > i; j--){
int currentCap = Math.min(height[i],height[j]) * (j - i);
if(currentCap > maxCap){
maxCap = currentCap;
}
}
}
return maxCap;
}
}
方法二:双指针
由于每次移动都使得容器的宽-1,所以我们需要使高变大。每次都舍弃当前较短的高,试图去找到一个更大的高。
class Solution {
public int maxArea(int[] height) {
//左侧指针
int left = 0;
//右侧指针
int right = height.length - 1;
//求出当前容量
int maxCap = Math.min(height[left],height[right]) * (right - left);
//当两侧指针重合就结束寻找
while(right > left){
//移动较低那侧的指针
if(height[left] < height[right]){
left++;
}else{
right--;
}
//判断容量是否变大
int currentCap = Math.min(height[left],height[right]) * (right - left);
if(currentCap > maxCap){
maxCap = currentCap;
}
}
return maxCap;
}
}
边栏推荐
- 【图形学】16 光照模型(一、理论与公式)
- NVIDIA CUDA Highly Parallel Processor Programming (8): Parallel Mode: Histogram Calculation
- Problem solving about Unity's button event response error triggering UI events
- VS2015MFC+SQLService版本的选择
- 神经网络和多元线性回归,神经网络多元线性回归
- Unity3D物体上下左右旋转(不受物体自身坐标轴影响)
- NVIDIA CUDA 高度并行处理器编程(六):并行模式:卷积
- Unity中获取一个物体下所有的子物体的方法
- P02 线程的用途
- [Unity] C#使用委托事件与字典实现unity消息中心(观察者模式)
猜你喜欢
随机推荐
P17 五子棋的实现4 悔棋功能
Lettcode链表OJ题分享以及讲解
By using the fgets () the number of rows in the statistics file and use the fgets ()/fputs () copy files
【图形学】15 UnityShader语义(三)
霍夫曼树(赫夫曼树、哈夫曼树)
排列组合题目小结
tcpdump进行DNS抓包
神经网络的图像识别技术,神经网络的层数怎么看
File IO realizes the encryption operation of pictures
Lettcode linked list OJ question sharing and explanation
Unity_雷达图(属性图)+ UI动画
Unity—ParticleSystem(粒子系统)与Animator(动画状态机)批量管理器
正则表达式入门要点知识总结
C语言实现冒泡排序及对冒泡排序的优化处理
封装,property伪类属性,多态,反射
【图形学】08 3D坐标系的变换(一)
Unity_圆环滑动条(圆形、弧形滑动条)
P21 美颜相机的实现——提速,重绘,撤回
神经网络二分类问题范例,神经网络解决分类问题
Unity学习笔记 02 —— 更多API