leet-code/src/main/java/leetcode/editor/cn/ContainerWithMostWater.java

87 lines
2.1 KiB
Java
Raw Normal View History

2021-05-03 18:25:28 +08:00
//给你 n 个非负整数 a1a2...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
//
//
//
//
// 提示:
//
//
// n = height.length
// 2 <= n <= 3 * 104
// 0 <= height[i] <= 3 * 104
//
// Related Topics 数组 双指针
// 👍 2425 👎 0
package leetcode.editor.cn;
//11:盛最多水的容器
public class ContainerWithMostWater {
public static void main(String[] args) {
//测试代码
Solution solution = new ContainerWithMostWater().new Solution();
//49
System.out.println(solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));
//1
System.out.println(solution.maxArea(new int[]{1, 1}));
//16
System.out.println(solution.maxArea(new int[]{4, 3, 2, 1, 4}));
//2
System.out.println(solution.maxArea(new int[]{1, 2, 1}));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int maxArea(int[] height) {
int start = 0;
int end = height.length - 1;
int max = 0;
while (start < end) {
max = Math.max(max, (end - start) * Math.min(height[start], height[end]));
if (height[start] < height[end]) {
start++;
} else {
end--;
}
}
return max;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}