盛最多水的容器
給你 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/276180.html
標籤:java
上一篇:每日一學:你知道如何在 RabbitMQ 中實作 Work queues作業佇列模式嗎?
下一篇:普歌-日期相關類
